<?php
namespace haibao\cms\data;

use haibao\frame\data\query\Condition;
use \haibao\cms\model\filter\Article as ArticleFilter;

class Article extends \haibao\cms\data\BaseMysql {
	private static $hcorrection = 'HC_ERROR_REPLACE';
	public function __construct() {
		parent::__construct ( '\haibao\cms\model\data\Article' );
	}
	
	const ARTICLE_CLICK = 6;
	
	public function getProductRelateArticleInfo($goodsId = null,$limit = 1){
	    $temp = '';
	    if($goodsId){
	        $temp = 'a.ProductId = %s AND ';
	    }
	    $sql = "SELECT
            	b.Id,b.PublishId,b.Title,b.Summary,c.PicUrl,d.ParentId
            FROM
            	ArticleProduct AS a
            LEFT JOIN Article AS b ON a.ArticleId = b.Id
            left join ArticleProImage as c on a.ArticleId=c.ArticleId
	        left join ArticleTag as d on b.Id = d.ArticleId
            WHERE ".$temp."
            	b.Title LIKE %s
            And b.Published = 1 and b.Status=0
            and c.PicType = 1 and c.`Level` = %s
            group by b.Id
            order by b.PublishTime desc
            limit %s";
	    if($goodsId){
	    	$result = $this->query($sql,array($goodsId,'%评测%',4,$limit))->fetch_assoc();
	    	if($result){
	    		return $result;
	    	}else {
	    		return  $this->query($sql,array($goodsId,'%评测%',0,$limit))->fetch_assoc();
	    	}  
	    }else{
	        $result = $this->query($sql,array('%评测%',6,$limit));
	        $relateEvaluatInfo = array();
	        while($row = $result->fetch_assoc()){
	            $relateEvaluatInfo[] = $row;
	        }
	        return $relateEvaluatInfo;
	    }
	    
	}
	
	/**
	 * 一周博主BestLook票选
	 * @param int $articleId
	 * @param int $type  1：刷新，2：换一组
	 */
	public function getBestLook($articleId, $type){
	    $where = '';
	    if($articleId && $type==1){
	        $where = ' and b.Id='.$articleId;
	    }elseif($articleId && $type==2){
	        $where = ' and b.Id<'.$articleId;
	    }
	    $sql = 'select b.Id,b.Title,b.Summary,b.PublishId,c.Id as voteId from ArticleTag as a 
	        left join Article as b on a.ArticleId=b.Id 
	        left join ArticleVote as c on b.Id=c.ArticleId 
	        where a.TagId=%s and b.`Status`=%s and b.Published=%s '.$where.' order by b.PublishTime desc limit 1';
	    $result = $this->query($sql, array(
	        8433, \haibao\cms\model\data\Article::STATUS_ENABLE, \haibao\cms\model\data\Article::PUBLISHED_YES
	    ));
	    $articleId = $pubId = $title = $summary = $voteId = null;
	    while ($result->fetch_assoc()){
	        $articleId = $result->getData('Id');
	        $pubId = $result->getData('PublishId');
	        $title = $result->getData('Title');
	        $summary = $result->getData('Summary');
	        $voteId = $result->getData('voteId');
	    }
	    
	    $result = $this->query('select Id,Title,OrderNum,VoteNum from ArticleVoteProperty where ArticleVoteId=%s order by OrderNum asc', array($voteId));
	    $imgArr = array();
	    while ($row = $result->fetch_assoc()){
	        $tmp = array();
	        $tmp['pid'] = $result->getData('Id');
	        preg_match('/<img src=\"(.*)" \/>(.*)/is', $result->getData('Title'), $arr);
	        if($arr){
    	        $tmp['imageUrl'] = $arr[1];
    	        $tmp['imageDescription'] = $arr[2];
	        }
	        $tmp['voteNum'] = $result->getData('VoteNum');
	        array_push($imgArr, $tmp);
	    }
	    return array(
	        'articleId' => $articleId,
	        'pubId' => $pubId,
	        'Title' => $title,
	        'Summary' => $summary,
	        'voteId' => $voteId,
	        'bestLook' => $imgArr
	    );
	}
	
	public function getTopTwoPvArticle($bannerIds){
		$data = array();
		$cache = new \haibao\cms\cache\Article();
		$hotArticle = $cache->getHotArticles();
		if (!$hotArticle){
			$articles = array();
			foreach ($bannerIds AS $ids){
				$sql = 'select t1.Id as Id,t1.PublishId as PublishId,t2.ParentId,t3.ClickNum,t2.ParentId as BannerId from Article t1';
				$sql .= ' inner join ArticleTag t2 on t1.Id=t2.ArticleId';
				$sql .= ' inner join ArticleProperty t3 on t1.Id = t3.ArticleId';
				$sql .= ' where t2.IsPrimaiy=1 and t2.ParentId in ('.implode(',',$ids).')';
				$sql .= ' and Published='.\haibao\cms\model\data\Article::PUBLISHED_YES;
				$sql .= ' and t1.PublishTime >="'.date('Y-m-d',strtotime('-7 days')).'" and t1.PublishTime <="'.date('Y-m-d H:i:s').'"';
				$sql .= ' order by t3.ClickNum desc limit 2';
				
				$result = $this->query($sql);
				$arr = array();
				while ($row = $result->fetch_assoc()){
					array_push($arr,$row['Id']);
					if (!isset($articles[$ids[0]])){
						$articles[$ids[0]] = array();
					}
					$articles[$ids[0]][$row['Id']] = array('Id'=>$row['Id'],'PublishId'=>$row['PublishId'],'BannerId'=>$ids[0],'Keywords'=>array());
				}
				
				if ($arr){
					$sql = 'select t1.ArticleId ArticleId,t2.Name Name from ArticleKeywords t1 inner join KeyWord t2 on t1.keywordId=t2.Id';
					$sql .= ' where t1.ArticleId in ('.implode(',',$arr).')';
					$result = $this->query($sql);
					while ($row = $result->fetch_assoc()){
						array_push($articles[$ids[0]][$row['ArticleId']]['Keywords'],$row['Name']);
					}
				}
				
				foreach ($articles as $bannerId=>$value){
					foreach ($value as $articleId=>$v){
						if (!$v['Keywords']){
							unset($articles[$bannerId][$articleId]);
						}
					}
					
					if (!$value){
						unset($articles[$bannerId]);
					}
				}
				
				$cache->setHotArticles(json_encode($articles));
				$hotArticle = $articles;
			}
		}else{
			$hotArticle = json_decode($hotArticle,true);
		}
		
		return $hotArticle;
	}
	
	public function getArticleImageById($articleId){
	    $sql = 'select ImageId from ArticleImage where ArticleId = %s';
	    $result = $this->query($sql,array($articleId));
	    $image = array();
	    while($row = $result->fetch_assoc()){
	        $image[] = $row['ImageId'];
	    }
	    return $image;
	}
	
	public function getArticleByTagId($tagId,$articleId = null,$limit=1){
		$except = '';
		if($articleId){
			$articleId = (array)$articleId;
			$articleId = implode(',',$articleId);
			$except = ' and a.Id not in ('.$articleId.') ';
		}
		$sql = "select a.Id,a.Title,a.PublishTime,a.PublishId from Article as a left join ArticleTag as b on a.Id = b.ArticleId where a.Status = 0 and a.Published = 1 and b.TagId = %s  $except order by a.PublishTime desc limit %s";
		
		if($limit == 1){
			$result = $this->query($sql, array($tagId,$limit))->fetch_assoc();
			return $result;
		}else{
			$resArr = array();
			$result = $this->query($sql, array($tagId,$limit));
			while($result->fetch_assoc()){
				$resArr[$result->getData('Id')]['Id'] = $result->getData('Id');
				$resArr[$result->getData('Id')]['Title'] = $result->getData('Title');
				$resArr[$result->getData('Id')]['PublishTime'] = $result->getData('PublishTime');
				$resArr[$result->getData('Id')]['PublishId'] = $result->getData('PublishId');
			}
			return $resArr;
		}

	}
	
	public function searchByKeywordFilter($filter){
		$data = array();
		$sengine = new \haibao\cms\sengine\SphinxDb();
		$result = $sengine->search($filter);
		
		if (!empty($result['matches'])){
			$filter->getPager()->setResultCount($result['total']);
			foreach ($result['matches'] as $match){
				array_push($data,$match['attrs']);
			}
		}
		
		return $data;
	}
	
	public function searchIdsByKeywordFilter($filter){
		$ids = array();
		$sengine = new \haibao\cms\sengine\SphinxDb();
		$result = $sengine->search($filter);
		
		if (!empty($result['matches'])){
			$filter->getPager()->setResultCount($result['total']);
			foreach ($result['matches'] as $match){
				array_push($ids,$match['attrs']['recordid']);
			}
		}
		 
		return $ids;
	}
	
	public function searchIdsByKeywordFilterForWap($filter){
		$ids = array();
		$sengine = new \haibao\cms\sengine\SphinxDb();
		$result = $sengine->search($filter);
		$filter->getPager()->setResultCount($result['total']);
		if (!empty($result['matches'])){
			foreach ($result['matches'] as $key=>$match){
				$ids[$key]['type'] = $match['attrs']['type'];
				$ids[$key]['recordid'] = $match['attrs']['recordid'];
				$ids[$key]['weight'] = $match['weight'];
			}
		}
			
		return $ids;
	}
	
	public static function searchUnionData($filter){
		$data = array();
		$sengine = new \haibao\cms\sengine\SphinxDb();
		$result = $sengine->search($filter);
		
		if (!empty($result['matches'])){
			foreach ($result['matches'] as $match){
				array_push($data,array('id'=>$match['attrs']['recordid'],'type'=>$match['attrs']['type']));
			}
			
			$filter->getPager()->setResultCount($result['total']);
		}
		
		return $data;
	}
	
	/**
	 * 添加文章
	 *
	 * @param \haibao\cms\model\data\Article $articleModel        	
	 */
	public function addArticle($articleModel) {
		self::beginTranscation ();
		try {
			
			$articleModel->PublishId = (int)$this->getMaxPublishId()+ 1;
			$this->add ( $articleModel );
			
			$channelTagId = $this->addArticleRelationTable ( $articleModel );
			$this->addArticleWap($articleModel,$channelTagId,true);
			//新库app推送
			if($articleModel->AppColum){
				$this->addArticleToApp($articleModel);
			}
			
		} catch ( \Exception $e ) {
			$this->rollback ();
			throw $e;
		}
		$this->endTranscation ();
		if (\haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\cms\Config::SYNC_OLD)) {
			// 老记录
			//$this->addOldArticleData($articleModel);
		}		
	}
	
	/**
	 * 获取最大的PublishId值
	 */
	public function getMaxPublishId(){
		$max = null;
		$result = $this->query("select max(PublishId) as PublishId from Article");
		while ($result->fetch_assoc()) {
			$max = $result->getData('PublishId');
		}
		return $max;
	}
	/**
	 * 修改文章信息
	 *
	 * @param \haibao\cms\model\data\Article $articleModel        	
	 * @throws Exception
	 */
	public function updateArticle($articleModel,$published) {
		self::beginTranscation ();
		try {
			$this->updateById($articleModel->Id, array(
					ArticleFilter::CONDITION_FIELD_NAME_TITLE=>$articleModel->Title,
					ArticleFilter::CONDITION_FIELD_NAME_SHORTTITLE=>$articleModel->ShortTitle,
					ArticleFilter::CONDITION_FIELD_NAME_SOURCE=>$articleModel->Source,
					ArticleFilter::CONDITION_FIELD_NAME_ISPSEUDONYM=>$articleModel->IsPseudonym,
					ArticleFilter::CONDITION_FIELD_NAME_SUMMARY=>$articleModel->Summary,
					ArticleFilter::CONDITION_FIELD_NAME_ARTICLE_CONTENT=>$articleModel->Content,
					ArticleFilter::CONDITION_FIELD_NAME_PUBLISHTIME=>$articleModel->PublishTime,
					ArticleFilter::CONDITION_FIELD_NAME_LEVEL=>$articleModel->Level,
					ArticleFilter::CONDITION_FIELD_NAME_PUBLISHED=>$articleModel->Published,
					ArticleFilter::CONDITION_FIELD_NAME_ARTICLE_SOURCE=>$articleModel->ArticleSource,
					ArticleFilter::CONDITION_FIELD_NAME_INDEX_TIME=>$articleModel->IndexTime			
					));
			
			$channelTagId = $this->addArticleRelationTable ( $articleModel, false );
			$this->addArticleWap($articleModel,$channelTagId,false);
			
			//新库app推送
			if($articleModel->AppColum){
				$this->addArticleToApp($articleModel);
			}
			
			if($published != $articleModel->Published && $articleModel->Published == \haibao\cms\model\data\Article::PUBLISHED_NO){
				$this->deleteInfomation($articleModel->Id,\haibao\cms\model\data\InformationStar::INFO_TYPE_ARTICLE);
				//操作聚合记录
				$data = new \haibao\cms\data\PolymerInfo();
				$data->updatePolymarInfo($articleModel->Id,\haibao\cms\model\data\PolymerInfo::OBJECT_TYPE_ARTICLE,array('Status'=>\haibao\cms\model\data\PolymerInfo::STATUS_DEL));
			}
			
		} catch ( \Exception $e ) {
			$this->rollback ();
			throw $e;
		}
		$this->endTranscation ();
		if (\haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\cms\Config::SYNC_OLD)) {
			// 老记录
			//$articleModelCopy = clone $articleModel;
			//$this->updateOldArticleData ($articleModelCopy);
		}
	}
	
	
	/**
	 * 添加手机文章表
	 */
	private function addArticleWap($articleModel,$channelTagId,$isAdd = true){
		if(!$articleModel->IsPostMobile && $articleModel->Published && $articleModel->Level > 0 && $articleModel->Status == \haibao\cms\model\data\Article::STATUS_ENABLE){
			$wapInfoModel = new \haibao\cms\model\data\WapInfo();
			$wapInfoModel->InfoId = $articleModel->Id;
			$wapInfoModel->Title = $articleModel->Title;
			$wapInfoModel->CreateBy = $articleModel->CreateBy;
			$wapInfoModel->CreateTime = $articleModel->CreateTime;
			$wapInfoModel->Author = $articleModel->Author; 
			$wapInfoModel->Published = \haibao\cms\model\data\WapInfo::PUBLISHED_YES;
			$wapInfoModel->PublishTime = $articleModel->PublishTime;
			$wapInfoModel->InfoType = $wapInfoModel::INFO_TYPE_ARTICLE;
			$wapInfoModel->IndexTop = $wapInfoModel::INDEX_TOP_NO;
			$wapInfoModel->ChannelTop = $wapInfoModel::CHANNEL_TOP_NO;
			$wapInfoModel->PublishId = $articleModel->PublishId;
			$wapInfoModel->Level = $articleModel->Level;
			$wapInfoModel->TagId = $channelTagId;
			$this->add($wapInfoModel);
			$sql = "update Article set IsPostMobile=%s where Id=%s";
			$this->query($sql,array(\haibao\cms\model\data\Article::PUBLISH_MOBILE_YES,$articleModel->Id));
		}
		if($articleModel->IsPostMobile){
			if($articleModel->Published){
				$sql = 'update WapInfo set Title=%s,Level=%s,TagId=%s,PublishTime=%s where InfoId=%s and InfoType=%s';
				$this->query($sql,array($articleModel->Title,$articleModel->Level,$channelTagId,$articleModel->PublishTime,$articleModel->Id,\haibao\cms\model\data\WapInfo::INFO_TYPE_ARTICLE));
			} else {
				$sql = 'delete from WapInfo where InfoId=%s and InfoType=%s';
				$this->query($sql,array($articleModel->Id,\haibao\cms\model\data\WapInfo::INFO_TYPE_ARTICLE));
				
				$sql = "update Article set IsPostMobile=%s where Id=%s";
				$this->query($sql,array(\haibao\cms\model\data\Article::PUBLISH_MOBILE_NO,$articleModel->Id));
			}
		}
	}
	
	
	/**
	 * 修改文章状态
	 *
	 * @param int $articleId        	
	 * @param int $status        	
	 */
	public function updateArticleStatus($articleId, $status = \haibao\cms\model\data\Article::STATUS_ENABLE) {
		$sql = 'update Article set Status=%s where Id=%s';
		$arrValues = array (
				$status,
				$articleId 
		);	
		$this->query ( $sql, $arrValues );
		if (\haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\cms\Config::SYNC_OLD)) {
			// 老记录
			//$this->updateOldArticleStatus ( $articleId, $status );
		}
	}
	
	/**
	 * 修改文章发布状态
	 * @param Array/int $articleId        	
	 * @param int $published  0:未发布，1：已经发布，2：预发布
	 */
	
	public function updateArticlePublish($articleId, $published = \haibao\cms\model\data\Article::PUBLISHED_YES,$oldPublished = null) {
		$sql = "";
		$this->setConfig(\haibao\classlibrary\www\Config::CLASSLIBRARY_CONFIG_MYSQL_HAIBAO_CMS);
		if (is_int ( $articleId )) {
			$sql = "update Article set Published=%s,IndexTime=%s where  Id=%s  ";
			$arrValues = array (
					$published,
					date('Y-m-d H:i:s'),
					$articleId					
			);			
			$this->query ( $sql, $arrValues );
		} elseif (is_array ( $articleId )) {
			$Ids = join(',',$articleId);
			$sql = "update Article set Published=".$published.",IndexTime='".date('Y-m-d H:i:s')."' where Id in (".$Ids.")  ";
			$this->query ( $sql );
		}
		
		if($oldPublished != $published && $published == \haibao\cms\model\data\Article::PUBLISHED_NO){
			$this->deleteInfomation($articleId,\haibao\cms\model\data\InformationStar::INFO_TYPE_ARTICLE);
			
			//操作聚会记录
			$data = new \haibao\cms\data\PolymerInfo();
			$data->updatePolymarInfo($articleId,\haibao\cms\model\data\PolymerInfo::OBJECT_TYPE_ARTICLE,array('Status'=>\haibao\cms\model\data\PolymerInfo::STATUS_DEL));
		}
		/* if (\haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\cms\Config::SYNC_OLD) && $sql) {
			// 老记录
			$this->updateOldArticlePublish ( $articleId, $published );
		} */
	}
	
	/**
	 * 删除infomation表中对应信息
	 * @param 文章/图集Id $articleId
	 * @param 类型 $intoType
	 */
	public function deleteInfomation($infoId,$infoType){
		$this->updateInfomationBrand($infoId, $infoType);
		$this->updateInformationStar($infoId, $infoType);
		$this->updateInformationDesigner($infoId, $infoType);
	}
	
	/**
	 * 通过文章id查找标签
	 */
	public function getArticleTagsByArticleId($articleId){
		$sql = "select TagId from ArticleTag where articleId = %s";
		$result = $this->query($sql,array($articleId));
		$tagIds = array();
		while($result->fetch_assoc()){
			array_push($tagIds,$result->getData('TagId'));
		}
		return $tagIds;
	}
	
	public function getArticleIsPublish($articleId){
		$sql = "select Id from Article where Id=%s and Published=1";
		$data  = $this->query($sql,array($articleId));
		$result = false;
		while ($data->fetch_assoc()){
			$result = true;
		}
		return $result;
	}
	
	/**
	 * 通过文章ids 获得点击数
	 */
	public function getClickNumsByArticleIds($articleIds){
		if(!$articleIds){
			return false;
		}
		$articleIds = (array)$articleIds;
		$articleIdStr = implode(',', $articleIds);
		$str = preg_replace('/(\d+)/', '%s', $articleIdStr);
		$sql = "select ArticleId,ClickNum,PcClickNum,MobileClickNum,PicClickNum from ArticleProperty where ArticleId IN (".$str.")";
		$result = $this->query($sql, $articleIds);
		$data = array();
		while ($result->fetch_assoc()){
			if(!isset($data[$result->getData('ArticleId')])){
				$data[$result->getData('ArticleId')]['ClickNum'] = $result->getData('ClickNum');
				$data[$result->getData('ArticleId')]['PcClickNum'] = $result->getData('PcClickNum');
				$data[$result->getData('ArticleId')]['MobileClickNum'] = $result->getData('MobileClickNum');
				$data[$result->getData('ArticleId')]['PicClickNum'] = $result->getData('PicClickNum');
			}
		}
		return $data;
	}
	/**
	 * 通过文章ids 获得点击数评论数
	 */
	public function getClickCommentNumsByArticleIds($articleIds){
		if(!$articleIds){
			return false;
		}
		$articleIds = (array)$articleIds;
		$articleIdStr = implode(',', $articleIds);
		$str = preg_replace('/(\d+)/', '%s', $articleIdStr);
		$sql = "select ArticleId,ClickNum,CommentNum,EditClickNum,ShareNum,MobileClickNum,PcClickNum,CommentPariseNum,QuestionNum,QuestionPariseNum from ArticleProperty where ArticleId IN (".$str.") order by EditClickNum desc";
		$result = $this->query($sql, $articleIds);
		$data = array();
		while ($result->fetch_assoc()){
			if(!isset($data[$result->getData('ArticleId')])){
				$nums = array(
						'clickNum'=>$result->getData('ClickNum'),
						'commentNum'=>$result->getData('CommentNum')+$result->getData('CommentPariseNum')+$result->getData('QuestionNum')+$result->getData('QuestionPariseNum'),
						'shareNum'=>$result->getData('ShareNum'),
						'editClickNum'=>$result->getData('EditClickNum'),
						'mobileClickNum'=>$result->getData('MobileClickNum'),
						'pcClickNum'=>$result->getData('PcClickNum')
						);
				$data[$result->getData('ArticleId')] = $nums;
			}
		}
		return $data;
	}
	public function updateArticleShareNum($articleId){
		$sql = "update ArticleProperty set ShareNum = ShareNum + 1 where ArticleId = %s";
		$this->query($sql,array($articleId));
		$shareNum = 0;
		$data = $this->getClickCommentNumsByArticleIds($articleId);
		if($data){
			$shareNum = $data[$articleId]['shareNum'];
		}
		return $shareNum;
	}
	/**
	 * 设置文章点击数
	 */
	public function updateArticleClickNum($articleId,$fromPc = true,$fromNotes = false){
	    $this->dealArticleClickNumData($articleId,self::ARTICLE_CLICK,$fromNotes,$fromPc);
// 		$setStr = '';
// 		if($fromPc){
// 			$setStr = ',PcClickNum=PcClickNum+1';
// 		} elseif($fromNotes){
// 		    $setStr = ',NotesClickNum=NotesClickNum+1';
// 		} else {
// 			$setStr = ',MobileClickNum=MobileClickNum+1';
// 		}
// 	    $sql = "update ArticleProperty set ClickNum=ClickNum+1,EditClickNum=EditClickNum+1".$setStr." where ArticleId=%s";
// 	    $result  = $this->query($sql,array($articleId));
	}
	
	public function dealArticleClickNumData($articleId,$type,$fromNotes = false,$fromPc = true,$isPic = false){
	    $dataList = array();
	    $dataList['articleId'] = $articleId;
	    $dataList['time'] = time();
	    if(!$fromPc && !$fromNotes){
	        $dataList['wap'] = 1;
	    }
	    if($fromNotes){
	        $dataList['notes'] = 1;
	    }
	    if($isPic){
	        $dataList['pic'] = 1;
	    }
	    $cacheData = new \haibao\cms\cache\ImageLibrary();
	    $cacheData->setArticleProperty($dataList);
	}
	
	public function updateArticleCommentNum($id,$num){
		$sql = "update ArticleProperty set CommentNum=CommentNum+".$num." where ArticleId=%s";
		$result  = $this->query($sql,array($id));
	}
	
	public function subtractCommentNum($id){
	    $sql = "update ArticleProperty set CommentNum =CommentNum-1  where ArticleId=%s";
		$this->query($sql,array($id));
	}
	
	public function getArticleIdByPublishId($pubishIds,$isLibrary){
		$pubishIds = (array)$pubishIds;
		$str = preg_replace('/(\d+)/', '%s', implode(',', $pubishIds));
		$sql = "select Id,PublishId from Article where PublishId in (".$str.")";
		$data  = $this->query($sql,$pubishIds);
		$result = array();
		if($isLibrary){
		    while ($data->fetch_assoc()){
		        $result[$data->getData('PublishId')] = $data->getData('Id');
		    }
		}else{
		    while ($data->fetch_assoc()){
		        $result[] = $data->getData('Id');
		    } 
		}
		return $result;
	}
	
	public function getArticleCommentNumAndVoteNum($articleId){
	    $sql = "select CommentNum,VoteNum,EditClickNum from ArticleProperty where ArticleId=%s";
	    $data  = $this->query($sql,array($articleId));
	    $result = array();
	    while ($data->fetch_assoc()){
	        $result['CommentNum'] = $data->getData('CommentNum');
	        $result['VoteNum'] = $data->getData('VoteNum');
	        $result['EditClickNum'] = $data->getData('EditClickNum');
	    }
	    return $result;
	}
	
	public function getArticleCommentNumAndVoteNumByIds($articleId){
	    $sql = "select ArticleId,CommentNum,VoteNum,EditClickNum from ArticleProperty where ArticleId in (".implode(',',$articleId).")";
	    $data  = $this->query($sql,$articleId);
	    $result = $row = array();
	    while ($data->fetch_assoc()){
	        $result['CommentNum'] = $data->getData('CommentNum');
	        $result['VoteNum'] = $data->getData('VoteNum');
	        $result['EditClickNum'] = $data->getData('EditClickNum');
	        $row[$data->getData('ArticleId')] = $result;
	    }
	    return $row;
	}
	
	public function getArticleByIds($articleIds){
	    $sql = 'select Id,PublishTime from Article where Id in ('.implode(',',$articleIds).') and Published = 1 and Status = 0';
	    $result = $this->query($sql,$articleIds);
	    $infoList = array();
	    while($row = $result->fetch_assoc()){
	        $infoList[$row['Id']] = $row['PublishTime'];
	    }
	    return $infoList;
	}
	
	/**
	 * 获取文章绑定图集Id
	 */
	public function getImageCollIdsByArticleIds($articleIds){
		$articleIds = (array)$articleIds;
		$articleIdStr = implode(',', $articleIds);
		$str = preg_replace('/(\d+)/', '%s', $articleIdStr);
		
		$sql = "select ArticleId,ImageCollectiveId from ImageCollectiveArticle where ArticleId IN (".$str.")";
		$result  = $this->query($sql,$articleIds);
		$data = array();
		while($result->fetch_assoc()){
			if(!isset($data[$result->getData('ArticleId')])){
				$data[$result->getData('ArticleId')] = $result->getData('ImageCollectiveId');
			}
		}
		return $data;
	}
	/**
	 * 修改文章等级
	 *
	 * @param int $articleId        	
	 * @param int $level        	
	 */
	public function updateArticleLevel($articleId, $level) {
		$sql = 'update Article set Level=%s where Id=%s';
		$arrValues = array (
				$level,
				$articleId 
		);
		$this->query ( $sql, $arrValues );
		$this->changeWapArticle($articleId, $level);
		
		if($level == 0){
			//操作聚合记录
			$data = new \haibao\cms\data\PolymerInfo();
			$data->updatePolymarInfo($articleId,\haibao\cms\model\data\PolymerInfo::OBJECT_TYPE_ARTICLE,array('Status'=>\haibao\cms\model\data\PolymerInfo::STATUS_DEL));
		}
		
		if (\haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\cms\Config::SYNC_OLD)) {
			// 老记录
			//$this->updateOldArticleLevel ( $articleId, $level );
		}
	}
	
	/**
	 * 前台ajax切换文章等级的时候相应得修改WapArticle表中数据
	 * @param int $articleId
	 * @param int $Level
	 */
	private function changeWapArticle($articleId,$Level){
		$updateSql = 'update WapInfo set Level=%s where InfoId = %s and InfoType=%s';
		$this->query($updateSql,array($Level,$articleId,\haibao\cms\model\data\WapInfo::INFO_TYPE_ARTICLE)); 
	}
	
	/**
	 * 修改文章审核状态
	 *
	 * @param int $articleId        	
	 * @param int $auditType        	
	 */
	public function updateArticleAuditType($articleId, $auditType = \haibao\cms\model\data\Article::AUDITTYPE_YES) {
		$sql = 'update Article set AuditType=%s where Id=%s';
		$arrValues = array (
				$auditType,
				$articleId 
		);
		$this->query ( $sql, $arrValues );
		if (\haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\cms\Config::SYNC_OLD)) {
			// 老记录
			//$this->updateOldArticleAuditType ();
		}
	}
	
	public function getShortTitleById($articleId){
		$sql="select ShortTitle from Article where Id=%s ";
		$result = $this->query($sql,array($articleId));
		$shortTitle = '';
		while($result->fetch_assoc()){
			$shortTitle = $result->getData('ShortTitle');
		}
		return $shortTitle;
	}
	
	/**
	 * 修改文章影响数
	 *
	 * @param int $articleId        	
	 * @param int $num        	
	 */
	public function updateEditClickNumByArticleId($articleId, $num) {
		$sql = 'update ArticleProperty set EditClickNum=%s where ArticleId=%s';
		$arrValues = array (
				$num,
				$articleId 
		);
		$this->query ( $sql, $arrValues );
		if (\haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\cms\Config::SYNC_OLD)) {
			// 老记录
			//$this->updateOldArticleEditClickNum($articleId,$num);
		}
	}
	
	/**
	 * 修改内容仓库
	 *
	 * @param int $id        	
	 * @param string $content        	
	 */
	public function updateContentDepot($id, $content) {
		$sql = 'update ContentDepot set Content=%s where Id=%s';
		$arrValues = array (
				$content,
				$id 
		);
		$this->query ($sql, $arrValues );
	}
	
	/**
	 * 错误内容替换
	 */
	public function errorContentReplace() {
		$contentReplaceArr = $this->getCache ( self::$hcorrection );
		if (empty($contentReplaceArr)) {
			$sql = "select Wrong,`Right` from ContentCorrection where Status = 1 ";
			$result = $this->query ( $sql );
			$contentReplaceArr = array();
			while ($result->fetch_assoc()){
				$contentReplaceArr['Wrong'][] = $result->getData('Wrong');
				$contentReplaceArr['Right'][] = $result->getData('Right');
			}
			if ($contentReplaceArr) {
				$this->setCache ( self::$hcorrection, $contentReplaceArr );
			} else {
				$this->setCache ( self::$hcorrection, 1 );
			}
		} else {
			if(!is_array($contentReplaceArr)){
				$contentReplaceArr = array();
			}
		}
		return $contentReplaceArr;
	}
	
	public function getArticleOldIdById($articleId){
		$sql="select OldPrimaryKey from DataMigrationMap where TableName = %s and PrimaryKey = %s ";
		$result = $this->query($sql,array('Article',$articleId))->fetch_assoc();
		return $result;
	}
	
	public function getArticleStatisticList($queryArr,$isEditorSta = true){
		$sql = "select a.CreateBy,a.Author,COUNT(DISTINCT a.Id) as ArticleCount,SUM(b.ClickNum) as ClickNum,SUM(b.VoteNum) as VoteNum,SUM(b.CommentNum) as CommentNum from Article as a";
		if(!$isEditorSta){
			$sql = "select Count(a.Id) as ArticleNum, SUM(b.ClickNum) as ClickNum, SUM(b.PcClickNum) as PcClickNum, SUM(b.MobileClickNum) as MobileClickNum,SUM(b.VoteNum) as VoteNum,SUM(b.CommentNum) as CommentNum from Article as a";
		}
		$sql .= " LEFT JOIN ArticleProperty as b on a.Id = b.ArticleId";
		if(!empty($queryArr['tagIds'])){
			$sql .= " LEFT JOIN ArticleTag as c on a.Id = c.ArticleId";
		}
		$sql .= " where a.CreateBy<>477";
		if(!empty($queryArr['createBy'])){
			if(is_array($queryArr['createBy'])){
				$sql .= " And a.CreateBy in (".implode(',', $queryArr['createBy']).")";
			} else {
				$sql .= " And a.CreateBy = ".$queryArr['createBy'];
			}
		}
		if(!empty($queryArr['tagIds'])){
			$sql .= " And c.TagId in (".$queryArr['tagIds'].")";
		}
		if(isset($queryArr['level'])){
			$level = (int)$queryArr['level'];
			if($level <= 7){
				$sql .= " And a.Level = ".$level;
			} else {
				$level = $level - 7;
				$sql .= " And a.Level >= ".$level;
			}
		}
		if(!empty($queryArr['title'])){
			$sql .= " And a.Title like '%".$queryArr['title']."%'";
		}
		if(!empty($queryArr['publishTimeType'])){
			$publishTimeType = (int)$queryArr['publishTimeType'];
			switch ($publishTimeType){
				case 1:
					$sql .= " And a.PublishTime >= '".date('Y-m-d', strtotime('-1 day'))."' And a.PublishTime <= '".date('Y-m-d',time())."'";
					break;
				case 2:
					$sql .= " And a.PublishTime >= '".date('Y-m-d', strtotime('-7 day'))."' And a.PublishTime <= '".date('Y-m-d',time())."'";
					break;
				case 3:
					$sql .= " And a.PublishTime >= '".date('Y-m-d', strtotime('-30 day'))."' And a.PublishTime <= '".date('Y-m-d',time())."'";
					break;
			}
		}
		
		if(!empty($queryArr['startDate'])){
			$sql .= " And a.PublishTime >= '".$queryArr['startDate']."'";
		}
		
		if(!empty($queryArr['endDate'])){
			$sql .= " And a.PublishTime <= '".$queryArr['endDate']."'";
		}
		
		$articleList = array();
		$listCount = 0;
		$articleNum = 0;
		$clickNum = 0;
		$pcClickNum = 0;
		$mobileClickNum = 0;
		$commentNum = 0;
		$voteNum = 0;
		if($isEditorSta){
			$sql .= " GROUP BY a.CreateBy";
		}
		$result = $this->query($sql);
		
		$listCount = 0;
		if(!$isEditorSta){
			while($result->fetch_assoc()){
				$clickNum = $result->getData('ClickNum');
				$pcClickNum = $result->getData('PcClickNum');
				$mobileClickNum = $result->getData('MobileClickNum');
				$commentNum = $result->getData('CommentNum');
				$voteNum = $result->getData('VoteNum');
				$articleNum = $result->getData('ArticleNum');
			}
		}else{
			$listCount = $result->getMysqlResult()->num_rows;
			while($result->fetch_assoc()){
				$articleNum = $articleNum + $result->getData('ArticleCount');
				$clickNum = $clickNum + $result->getData('ClickNum');
				$pcClickNum = $pcClickNum + $result->getData('PcClickNum');
				$mobileClickNum = $mobileClickNum + $result->getData('MobileClickNum');
				$commentNum = $commentNum + $result->getData('CommentNum');
				$voteNum = $voteNum + $result->getData('VoteNum');
			}
			$orderStr = " order by ArticleCount desc";
			if(!empty($queryArr['orderType'])){
				$orderType = (int)$queryArr['orderType'];
				$orderVal = $queryArr['orderVal'];
				if(empty($orderVal)){
					$orderVal = "";
				} else {
					$orderVal = "desc";
				}
				switch ($orderType){
					case 1:
						$orderStr = " order by ClickNum ".$orderVal;
						break;
					case 2:
						$orderStr = " order by VoteNum ".$orderVal;
						break;
					case 3:
						$orderStr = " order by CommentNum ".$orderVal;
						break;
					case 4:
						$orderStr = " order by ArticleCount ".$orderVal;
						break;
					default:
						$orderStr = " order by a.PublishTime ".$orderVal;
						break;
				}
			}
			$sql .= $orderStr;
			$limit ="";
			if(!isset($queryArr['source'])){
				$limit = " Limit 0,20";
				if(!empty($queryArr['page']) && $queryArr['page'] > 1){
					$startCount = ($queryArr['page'] - 1) * 20 + 1;
					$limit = " Limit ".$startCount.",20";
				}
			}
			$sql .= $limit;
			$result = $this->query($sql);
			$k = 0;
			while($result->fetch_assoc()){
				$articleList[$k]['Author']=$result->getData('Author');
				$articleList[$k]['UserId']=$result->getData('CreateBy');
				$articleList[$k]['ArticleCount']=$result->getData('ArticleCount');
				$articleList[$k]['ClickNum']=$result->getData('ClickNum');
				$articleList[$k]['PcClickNum']=$result->getData('PcClickNum');
				$articleList[$k]['MobileClickNum']=$result->getData('MobileClickNum');
				$articleList[$k]['CommentNum']=$result->getData('CommentNum');
				$articleList[$k]['VoteNum']=$result->getData('VoteNum');
				$k++;
			}
		}
		
		return array('List'=>$articleList,'Count'=>$listCount,'ArticleNum'=>$articleNum,'ClickNum'=>$clickNum,'pcClickNum'=>$pcClickNum,'mobileClickNum'=>$mobileClickNum,'CommentNum'=>$commentNum,'VoteNum'=>$voteNum);
	}
	
	/**
	 * 公用用新文章id获得新图片id
	 * @param $articleIds array or int or string
	 */
	public function publicImageIdByArticleId($articleId){
		
		$sql="select ImageId from ArticleImage where ArticleId = %s order by PicOrder asc";
		$result = $this->query($sql,array($articleId))->fetch_assoc();
		return $result;
	}
	
	public function getProImageByArticleId($articleId){
		$sql="select ImageId,PicType,Level,PicUrl from ArticleProImage where ArticleId = %s ";
		$result = $this->query($sql,array($articleId));
		$proImags=array();
		$key=0;
		while($result->fetch_assoc()){		
			$proImags[$key]['ImageId']=$result->getData('ImageId');
			$proImags[$key]['PicType']=$result->getData('PicType');
			$proImags[$key]['Level']=$result->getData('Level');	
			$proImags[$key]['PicUrl']=$result->getData('PicUrl');	
			$key++;
		}		
		return $proImags;
	}
	
	public function getProImageByCollectiveId($collectiveId,$imageType){
		$sql = "SELECT il.Id as proId,il.FileName AS proImage FROM ImageCollectivePro icp LEFT JOIN ImageLibrary il ON icp.ImageId = il.Id WHERE icp.ImageCollectiveId = %s AND icp.ImageType = ".$imageType;
		$result = $this->query($sql,array($collectiveId));
		$proImage = array();
		while($result->fetch_assoc()){
			$proImage['proImage'] = $result->getData('proImage');
			$proImage['proId'] = $result->getData('proId');
		}
		return $proImage;
	}
	
	/**
	 * 取得海报聚焦的资讯图片显示 
	 * @param unknown $articleId    资讯或者图集的Id
	 * @param unknown $picLevel		要获取导读图的等级
	 * @param unknown $type			资讯或者图集
	 */
	public function getFocusImageListByArticleId($articleId,$picLevel,$type=\haibao\cms\model\data\FocusImage::ARTICLE_TYPE){
		if($type == \haibao\cms\business\control\Base::DATA_TYPE_ARTICLE){
		    $proImageZero = array();
		    $zeroImageId = '';
			$proImage = $this->getProImageByArticleId($articleId);
			$picLevel = $picLevel ? $picLevel : \haibao\cms\model\data\ArticleProImage::Level_ZERO;
			$images = $defaultImages = array();$imageId = 0;
			foreach ($proImage as $list){
				if($list['Level'] == $picLevel && $list['PicType'] == \haibao\cms\model\data\ArticleProImage::PIC_TYPE_INTRO){
					$images[] = $list['PicUrl'];
					$imageId = $list['ImageId'];
				}
				if($list['Level'] == 0 && $list['PicType'] == \haibao\cms\model\data\ArticleProImage::PIC_TYPE_INTRO){
					$proImageZero[] = $list['PicUrl'];
					$zeroImageId = $list['ImageId'];
				}
			}
			$images = empty($images)?$proImageZero:$images;
			$imageId = $imageId?$imageId:$zeroImageId;
			$focusImages = $this->getImagesFromFocusImage($articleId,\haibao\cms\model\data\FocusImage::ARTICLE_TYPE);
			if ($focusImages) {
				return array_merge($images,$focusImages);
			}else{
				$data = new \haibao\cms\data\Article();
				$sql = "select PicUrl from ArticleImage where ImageId <> %s and ArticleId=%s order by Id desc limit 0,4";
				$result = $data->query($sql,array_merge(array($imageId,$articleId)));
				while($result->fetch_assoc()){
					$defaultImages[] = $result->getData("PicUrl");
				}
				return array_merge($images,$defaultImages);
			}
		}else{
			$proImage = $this->getProImageByCollectiveId($articleId, $picLevel);
			if(empty($proImage)){
				$proImage = $this->getProImageByCollectiveId($articleId, 0);
			}
			$focusImages = $this->getImagesFromFocusImage($articleId,\haibao\cms\model\data\FocusImage::IMAGE_COLLECTIVE_TYPE);
			if ($focusImages) {
				return array_merge(array($proImage['proImage']),$focusImages);
			}else{
				$data = new \haibao\cms\data\ImageLibrary();
				$sql = "SELECT icp.Id AS cid, il.FileName AS ImageUrl FROM ImageCollectivePic icp LEFT JOIN ImageLibrary il ON icp.ImageId = il.Id WHERE icp.ImageId <> %s AND icp.ImageCollectiveId = %s ORDER BY cid LIMIT 0,4";
				$result = $data->query($sql,array_merge(array($proImage['proId']),array($articleId)));
				while($result->fetch_assoc()){
					$defaultImages[] = $result->getData("ImageUrl");
				}
				return array_merge(array($proImage['proImage']),$defaultImages);
			}
		}
		
	}
	
	/**
	 * 获取资讯后台手动设置的显示图片
	 */
	private function getImagesFromFocusImage($infoId,$infoType){
		$sql = "select ImageId,PicUrl from FocusImage where InfoId= %s and InfoType=%s";
		$result = $this->query($sql,array($infoId,$infoType));
		$images = array();
		while($result->fetch_assoc()){
			$images[] = $result->getData("PicUrl");
		}
		return $images;
	}

	/**
	 * 根据InfoId获取FocusImage里的图片
	 */
	public function getImageIdsFromFocus($infoId,$infoType){
		$sql = "select ImageId from FocusImage where InfoId=%s and InfoType=%s";
		$result = $this->query($sql,array($infoId,$infoType));
		$imageIds = array();
		while ($result->fetch_assoc()){
			$imageIds[] = $result->getData('ImageId');
		}
		return $imageIds;
	}
	/**
	 * 得文章导读图
	 * @param array $articleIds
	 * @param int $level
	 * @return array(ArticleId=>ImageId)
	 */
	public function getProImageFigure($articleIds,$level){
		if(count($articleIds) == 1){
			$sql = "select ArticleId,ImageId,PicUrl from `ArticleProImage` where `ArticleId` = ".$articleIds[0]." and level = ".$level." and `PicType` =1";
			$result = $this->query($sql, $articleIds);
		} else {
			$str = preg_replace('/(\d+)/', '%s', implode(',', $articleIds));
			$sql = "select ArticleId,ImageId,PicUrl from `ArticleProImage` where `ArticleId` in (".$str.") and level = ".$level." and `PicType` =1";
			$result = $this->query($sql, $articleIds);
		}
		
		
		$proImags = array();
		while($result->fetch_assoc()){
			$proImags[$result->getData('ArticleId')]['PicUrl'] = $result->getData('PicUrl');
			$proImags[$result->getData('ArticleId')]['ImageId'] = $result->getData('ImageId');
		}
		return $proImags;
	}
	/**
	 * 获取第一张图
	 */
	public function getFirstPic($articleIds){
		$str = preg_replace('/(\d+)/', '%s', implode(',', $articleIds));
		$sql = "select `ArticleId`,`ImageId`,`PicUrl` from `ArticleImage` where `ArticleId` in (".$str.") and `PicOrder` = 1";
		$result = $this->query($sql, $articleIds);
		$firstImgIds= array();
		while($result->fetch_assoc()){
			if(!isset($firstImgIds[$result->getData('ArticleId')])){
				$firstImgIds[$result->getData('ArticleId')]['PicUrl'] = $result->getData('PicUrl');
				$firstImgIds[$result->getData('ArticleId')]['ImageId'] = $result->getData('ImageId');
			}
		}
		return $firstImgIds;
	}
	
	/**
	 * 设置文章图片类型（导读图/封面图）
	 * @param : int $articleId 文章ID
	 * @param : object $imageInfo 图片信息
	 * @param : int $imgType 图片类型
	 * @param : int $level 等级
	 */
	public function setImageType($articleId,$imageInfo,$imgType,$level){
		$sql = 'delete from `ArticleProImage` where ArticleId=%s and PicType=%s and Level=%s';
		$this->query($sql,array($articleId,$imgType,$level));

		$sql = 'insert into `ArticleProImage` (ArticleId,ImageId,PicType,Level,Width,Height,PicUrl) values (%s,%s,%s,%s,%s,%s,%s)';
		$valArr = array();
		array_push($valArr,$articleId);
		array_push($valArr,$imageInfo->Id);
		array_push($valArr,$imgType);
		array_push($valArr,$level);
		array_push($valArr,$imageInfo->Width);
		array_push($valArr,$imageInfo->Height);
		array_push($valArr,$imageInfo->Filename);
		$this->query($sql,$valArr);
		$insertId = $this->getDb()->insert_id;
		
		//操作聚合页面
		if($imgType == \haibao\cms\model\data\ArticleProImage::PIC_TYPE_INTRO){
			$data = new \haibao\cms\data\PolymerInfo();
			$polymerInfoModel = $data->getPolymerInfo($articleId,\haibao\cms\model\data\PolymerInfo::OBJECT_TYPE_ARTICLE);
			if(!empty($polymerInfoModel) && $polymerInfoModel->Status == \haibao\cms\model\data\PolymerInfo::STATUS_OK){
				$arrSet = array();
				$arrSet['UpdateType'] = \haibao\cms\model\data\PolymerInfo::UPDATE_TYPE_TITLE;
				$arrSet['Status'] = \haibao\cms\model\data\PolymerInfo::STATUS_EDIT;
				$data->updatePolymarInfo($articleId,\haibao\cms\model\data\PolymerInfo::OBJECT_TYPE_ARTICLE,$arrSet);
			}
		}
		
		return $insertId;
	}
	/**
	 * 删除文章自定义导读图
	 * @param : int $imageProId
	 */
	public function delProImageByProId($imageProId){
		$sql = 'select ArticleId,Level from `ArticleProImage` where Id=%s';
		$result = $this->query($sql,array($imageProId))->fetch_assoc();
			if($result){
				$sql = 'delete from `ArticleProImage` where Id=%s';
				$this->query($sql,array($imageProId));
			
			if (\haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\cms\Config::SYNC_OLD)) {
				if($result['Level'] <=3){
				// 老记录
				//$this->delOldProImageByProId($result['ArticleId'],$result['Level']);
				}
			}
		}
	}
	
	/**
	 * 删除文章标签
	 * @param int $articleId
	 * @param int $tagId
	 * @throws BusinessException
	 */
	public function delArticleTag($articleId,$tagId){
		$sql = 'delete from `ArticleTag` where ArticleId=%s and TagId=%s';
		$this->query($sql,array($articleId,$tagId));
		if (\haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\cms\Config::SYNC_OLD)) {
			// 老记录
			//$this->delOldArticleTag($articleId,$tagId);
		}
	}
	
	public function batchUpdateAircleTag($articleModel){
		$this->initNewDB();
		$this->addArticleTag($articleModel->ArticleTag, $articleModel->Id);
		if (\haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\cms\Config::SYNC_OLD)) {
			//$article = $this->getOneById($articleModel->Id);
			//$article->ArticleTag = $articleModel->ArticleTag;
			// 老记录
			//$sql = 'select OldPrimaryKey from DataMigrationMap where TableName = %s and PrimaryKey =%s';
			//$result = $this->query($sql,array('Article',$articleModel->Id))->fetch_assoc();
			//$documentId = $result['OldPrimaryKey'];
			//没有找到新-老关系对应记录
			//if(empty($documentId)) return NULL;
			//$this->saveOldArticleTag ( $article, $documentId ,false);
		}
	}
	/**
	 * 检查文章是否有此标签
	 */
	public function checkArticleTags($articleIds,$tagIds){
		$tagStr = preg_replace('/(\d+)/', '%s', implode(',', $tagIds));
		$idStr = preg_replace('/(\d+)/', '%s', implode(',', $articleIds));
		$sql = "select `ArticleId`,`TagId` from `ArticleTag` where `TagId` in (".$tagStr.") and `ArticleId` in (".$idStr.")";
		$result = $this->query($sql, array_merge($tagIds, $articleIds));
		$articleTag= array();
		while($result->fetch_assoc()){
			if(!isset($articleTag[$result->getData('ArticleId')][$result->getData('TagId')])){
				$articleTag[$result->getData('ArticleId')][] = $result->getData('TagId');
			}
		}
		return $articleTag;
	}
	/**
	 * 获取文章封面图
	 */
	public function getCoverImageFigure($articleId){
		$sql = "select ArticleId,PicUrl,ImageId,Level from ArticleProImage where ArticleId =%s and level in (".\haibao\cms\model\data\ArticleProImage::Level_ZERO.",".\haibao\cms\model\data\ArticleProImage::COVER_LEVEL_ONE.") and PicType = %s";
		$result = $this->query($sql,array($articleId,\haibao\cms\model\data\ArticleProImage::PIC_TYPE_COVER));

		$image = $coverImage = array();
		while($result->fetch_assoc()){
			$articleId = $result->getData('ArticleId');
			$coverImage[$result->getData('Level')] = $result->getData('ImageId');
		}
		if(array_key_exists(\haibao\cms\model\data\ArticleProImage::COVER_LEVEL_ONE, $coverImage)){
			$image[$articleId] = $coverImage[\haibao\cms\model\data\ArticleProImage::COVER_LEVEL_ONE];
		}else{
			if(isset($coverImage[\haibao\cms\model\data\ArticleProImage::Level_ZERO])){
				$image[$articleId] = $coverImage[\haibao\cms\model\data\ArticleProImage::Level_ZERO];
			}else{
				$image[$articleId] = '';
			}
		}
		return $image;
	}
	
	/**
	 * 预发布/发布中文章id
	 */
	public function getCronArticleId($published){		
		$articleId=array();
		if($published == \haibao\cms\model\data\Article::PUBLISHED_ING){
			$sql="select Id from Article where Published = %s and Status = 0";
		}else{
			$today = date('Y-m-d H:i:s',time());
			$sql="select Id from Article where Published = %s and Status = 0 and PublishTime<='".$today."' ";
		}
		$result = $this->query($sql,array($published));
		while($result->fetch_assoc()){
			$articleId[] = $result->getData('Id');
		}
		return $articleId;
	}
	
	public function getNoPublishAritcleId($maxId){
		$articleId=array();
		$sql="select Id from Article where Published = 0 and PublishId > 0 and Level=2 and Id>".$maxId.' order by Id desc';
		$result = $this->query($sql);
		while($result->fetch_assoc()){
			$articleId[] = $result->getData('Id');
		}
		return $articleId;
	}
	
	/**
	 * 文章发布信息存入数据库 用于计划任务同步FTP
	 * @param Int $articleId
	 * @param  Array $synchroArr 同步数据
	 */
	public function articlePublishSynchro($articleId, $synchroArr){
		
		$sql = "delete from `ArticlePublish` where ArticleId=%s";
		$this->query($sql,array($articleId));

		$sql = "insert into `ArticlePublish` (ArticleId,LocalFileName,TagDomain) values";
		$sqlArr = $valArr = array();
		foreach($synchroArr as $arr){
			array_push($sqlArr,'(%s,%s,%s)');
			array_push($valArr,$arr['articleId']);
			array_push($valArr,$arr['localFileName']);
			array_push($valArr,$arr['topTagDomain']);
		}
		$sql .= implode(',',$sqlArr);
		$this->query($sql,$valArr);
	}
	
	public function articlePublishSynchroMigrate($articleId, $synchroArr){
	
		$sql = "delete from `ArticlePublishMigrate` where ArticleId=%s";
		$this->query($sql,array($articleId));
	
		$sql = "insert into `ArticlePublishMigrate` (ArticleId,LocalFileName,TagDomain) values";
		$sqlArr = $valArr = array();
		foreach($synchroArr as $arr){
			array_push($sqlArr,'(%s,%s,%s)');
			array_push($valArr,$arr['articleId']);
			array_push($valArr,$arr['localFileName']);
			array_push($valArr,$arr['topTagDomain']);
		}
		$sql .= implode(',',$sqlArr);
		$this->query($sql,$valArr);
	}
	
	/**
	 * 获取图片进入浏览模式图片ID（目前使用老库文章关联图片ID）
	 * @param unknown $oldArticleId
	 */
	public function getPicBrowse($oldArticleId){
		
		$this->initOldDB();
		$sql="select id from `content_photo` where article_id=%s and disrel=0 order by id asc limit 1";
		return $this->query($sql,array($oldArticleId))->fetch_assoc();
	}
	
	/**
	 * 添加文章关系表
	 *
	 * @param \haibao\cms\model\data\Article $articleModel
	 * @param bool $isAdd
	 */
	private function addArticleRelationTable($articleModel, $isAdd = true) {
		$isEdit = true;
		if($isAdd){
			$isEdit = false;
		}
		$channelTagId = $this->addArticleTag ( $articleModel->ArticleTag, $articleModel->Id, $isEdit );
		
		//$this->addImageCollectiveArticle($articleModel->ArticleImageCollective,$articleModel->Id);
		
		$this->addEventArticle($articleModel->ArticleEvent,$articleModel->Id);
		
		$contentPageIdArr = $this->addArticleContent ( $articleModel->ArticleContent, $articleModel->Id, $isEdit );
	
		$this->addArticleProduct ( $articleModel->ArticleProduct, $articleModel->Id, $contentPageIdArr, $isEdit );
		
		$this->addArticleImage ( $articleModel->ArticleImage, $articleModel->Id, $contentPageIdArr, $isEdit );
	
		//if($isAdd){
			$this->addArticleProImage ( $articleModel->ArticleProImage, $articleModel->Id);
		//}
		//$this->addArticleKeyword ($articleModel->ArticleKeywords,$articleModel->Id);
		if ($isAdd) {
			$articleModel->ArticleProperty = new \haibao\cms\model\data\ArticleProperty();
			$articleModel->ArticleProperty->ArticleId = $articleModel->Id;
			$articleModel->ArticleProperty->ClickNum = 0;
			$articleModel->ArticleProperty->CommentNum = 0;
			$articleModel->ArticleProperty->VoteNum = 0;
			$articleModel->ArticleProperty->EditClickNum = 0;
			$articleModel->ArticleProperty->ShareNum = 0;
			$articleModel->ArticleProperty->PcClickNum = 0;
			$articleModel->ArticleProperty->MobileClickNum = 0;
			$articleModel->ArticleProperty->PicClickNum = 0;
			
			$this->add ( $articleModel->ArticleProperty );
		}
		
		return $channelTagId;
	}
	public  function addImageCollectiveArticle($articleImageCollectiveModel,$articleId){	
			
		$sql="delete from ImageCollectiveArticle where ArticleId = %s";
		$this->query($sql,array($articleId));	
		if($articleImageCollectiveModel){
			$articleImageCollectiveModel->ArticleId = $articleId;
			$this->add($articleImageCollectiveModel);
		}
	}
	
	public function getCountArticlesByCreateBy($userIds){
		$str = preg_replace('/(\d+)/', '%s', implode(',', $userIds));
		$daysAgo = date('Y-m-d 00:00:00',strtotime('-7 days'));
		$sql = "SELECT CreateBy,Author,count(*) as Counts FROM Article WHERE PublishTime>'".$daysAgo."' AND CreateBy IN (".$str.") GROUP BY CreateBy";
		$result = $this->query($sql,$userIds);
		$countArr = array();
		while($result->fetch_assoc()){
			$countArr[$result->getData('CreateBy')] = array('Author'=>$result->getData('Author'),'Counts'=>$result->getData('Counts'));
		}
		return $countArr;
	}
	
	
	public function getPropertyByCreateBy($userIds){
		$str = preg_replace('/(\d+)/', '%s', implode(',', $userIds));
		$daysAgo = date('Y-m-d 00:00:00',strtotime('-7 days'));
		$sql = "SELECT A.CreateBy CreateBy,SUM(AP.ClickNum) as SumClick,SUM(AP.CommentNum) as SumComment FROM `Article` A LEFT JOIN `ArticleProperty` AP  ON A.Id = AP.ArticleId WHERE A.PublishTime>'".$daysAgo."' and A.CreateBy in (".$str.") GROUP BY CreateBy";
		$result = $this->query($sql,$userIds);
		$propertyArr = array();
		while($result->fetch_assoc()){
			$propertyArr[$result->getData('CreateBy')] = array('ClickNum'=>$result->getData('SumClick'),'CommentNum'=>$result->getData('SumComment'));
		}
		return $propertyArr;
	}
	
	/**
	 * 更新文章发布ID
	 * @param unknown_type $articleId
	 */
	private function updatePublistId($articleId,$publicId = 0){
		if(empty($publicId)){
			$publicId = $articleId;
		}
		$sql = "update Article set PublishId=".$publicId." where Id =".$articleId;
		$this->query ( $sql );
		
		$sql = "update WapInfo set PublishId=".$publicId." where InfoId =".$articleId." and InfoType=".\haibao\cms\model\data\WapInfo::INFO_TYPE_ARTICLE;
		$this->query ( $sql );
	}
	
	public function addArticleKeyword($articleKeywrodModels,$articleId){
		$sql ="delete from ArticleKeywords where ArticleId = %s";
		$this->query($sql,array($articleId));
		if ($articleKeywrodModels) {
			foreach ( $articleKeywrodModels as $key => $keywordModel ) {
				if($keywordModel->KeywordId){
					$keywordModel->ArticleId = $articleId;
				}else{
					unset($articleKeywrodModels[$key]);
				}
			}
		}
		if ($articleKeywrodModels) {
			$this->addAll ( $articleKeywrodModels );
		}
	}
	private function addArticleProperty($articlePropertyModel, $articleId) {
		$articlePropertyModel->ArticleId = $articleId;
		$this->add ( $articlePropertyModel );
	}
	private function addArticleProImage($articleProImageModels, $articleId) {
		
		$isAdd = false;
		$sql = "select Id from ArticleProImage where ArticleId = %s AND level =0 limit 1";
		$result = $this->query($sql,array($articleId))->fetch_assoc();
		if ($articleProImageModels && !$result) {
			$isAdd = true;
			foreach ( $articleProImageModels as $key => $proImageModel ) {
				$proImageModel->ArticleId = $articleId;
			}
		}
		if ($articleProImageModels && $isAdd) {
			$this->addAll ( $articleProImageModels );
		}
		
		// 文章内容为空 则需要删除文章关联的所有导读图
		if(!$articleProImageModels){
			$sql = "delete from ArticleProImage where ArticleId = %s";
			$this->query($sql,array($articleId));
		}
	}
	
	public function addArticleTag($articleTagModels, $articleId, $isEdit = false) {
		$channelTagId = 0;
		if ($isEdit) {
			$sql = 'delete from ArticleTag where ArticleId=%s';
			$this->query ( $sql, array (
					$articleId 
			) );
		} 

		if ($articleTagModels) {
			$tagIds = array();
			foreach ( $articleTagModels as $key => $tagModel ) {
				if($tagModel->TagId){
					$tagIds[] = $tagModel->TagId;
					$tagModel->ArticleId = $articleId;
					$articleTagModels [$key] = $tagModel;
					if($tagModel->IsPrimaiy){
						$channelTagId = $tagModel->ParentId;
					}else{
					    $tagModel->IsPrimaiy = 0;
					}
				}else{
					unset($articleTagModels [$key]);
				}
			}
			$tagTrees = \haibao\cms\business\Tag::loopGetParentTag($tagIds);
			foreach($articleTagModels as $key=>$tagModel){
				$tagModel->TagTree = isset($tagTrees[$tagModel->TagId]) ? $tagTrees[$tagModel->TagId] : '#';
			}
		}
		if ($articleTagModels) {
			$this->addAll ( $articleTagModels );
		}
		
		return $channelTagId;
	}
	private function addArticleContent($articleContentModels, $articleId, $isEdit = false) {
		$contentPageIdArr = array ();
		if ($isEdit) {
			$sql = 'delete from ArticleContent where ArticleId=%s';
			$this->query ( $sql, array (
					$articleId 
			) );
		}
		if ($articleContentModels) {
			foreach ( $articleContentModels as $key => $contentModel ) {
				if($contentModel->Content){
					$contentModel->ArticleId = $articleId;
					$this->add ( $contentModel );
					$contentPageIdArr [$contentModel->CurrentPage] = $contentModel->Id;
				}
			}
		}
		
		return $contentPageIdArr;
	}
	private function addArticleProduct($articleProductModels, $articleId, $contentPageIdArr, $isEdit = false) {
		if ($isEdit) {
			$sql = 'delete from ArticleProduct where ArticleId=%s';
			$this->query ( $sql, array (
					$articleId 
			) );
		}
		
		if ($articleProductModels) {
			foreach ( $articleProductModels as $key => $productModel ) {
				$productModel->ArticleId = $articleId;
				if (! empty ( $contentPageIdArr [$productModel->CurrentPage] )) {
					$productModel->ArticleContentId = $contentPageIdArr [$productModel->CurrentPage];
				}
				$articleProductModels [$key] = $productModel;
			}
			$this->addAll ( $articleProductModels );
		}
	}
	private function addArticleImage($articleImageModels, $articleId, $contentPageIdArr, $isEdit = false) {
		if ($isEdit) {
			$sql = 'delete from ArticleImage where ArticleId=%s';
			$this->query ( $sql, array (
					$articleId 
			) );
		}
		
		if ($articleImageModels) {
			foreach ( $articleImageModels as $key => $imageModel ) {
				$imageModel->ArticleId = $articleId;
				if (! empty ( $contentPageIdArr [$imageModel->CurrentPage] )) {
					$imageModel->ArticleContentId = $contentPageIdArr [$imageModel->CurrentPage];
				}
				$articleImageModels [$key] = $imageModel;
			}
			$this->addAll ( $articleImageModels );
		}
	}
	public function getArticleAppCloumn($articleId){
			$sql = 'select `column_id` from `AppArticleCategory` where `document_id`=%s';
			$result = $this->query ( $sql, array ($articleId));
			$appCloumn = array();
			while ($result->fetch_assoc()){
			   array_push($appCloumn, $result->getData('column_id'));
		    }
		    return $appCloumn;
	}
	
	/**
	 * 通过文章ID得到它的主标签ID
	 * @param array $articleIds
	 * @return array(Article=>TagId)
	 */
	public function getArticlePrimaryTag($articleIds){
		$str = preg_replace('/(\d+)/', '%s', implode(',', $articleIds));
		$sql = "select `ArticleId`,`TagId` from `ArticleTag` where `ArticleId` in (".$str.") and `IsPrimaiy` =1";
		$result = $this->query($sql, $articleIds);
		$primaryTag = array();
		while ($result->fetch_assoc()){
			$primaryTag[$result->getData('ArticleId')] = $result->getData('TagId');
		}
		return $primaryTag;
	}
	
	/**
	 * 通过文章ID得到它的顶级ID
	 * @param array $articleIds
	 * @return array(Article=>TagId)
	 */
	public function getArticleTopTag($articleIds){
	    $str = preg_replace('/(\d+)/', '%s', implode(',', $articleIds));
	    $sql = "select `ArticleId`,`ParentId` from `ArticleTag` where `ArticleId` in (".$str.") and `IsPrimaiy` =1";
	    $result = $this->query($sql, $articleIds);
	    $primaryTag = array();
	    while ($result->fetch_assoc()){
	        $primaryTag[$result->getData('ArticleId')] = $result->getData('ParentId');
	    }
	    return $primaryTag;
	}
	
	public function getPublishedArticleIds($articleIds){
		$articleFilter = new ArticleFilter();
		$articleFilter->select(array(ArticleFilter::CONDITION_FIELD_NAME_ID));
		$articleFilter->where(ArticleFilter::CONDITION_FIELD_NAME_ID, Condition::CONDITION_IN, $articleIds);
		$articleFilter->where(ArticleFilter::CONDITION_FIELD_NAME_PUBLISHED, Condition::CONDITION_EQUAL, \haibao\cms\model\data\Article::PUBLISHED_YES);
		$result = $this->getAll($articleFilter);
		$Ids = array();
		if($result){
			foreach($result as $article){
				array_push($Ids, $article->Id);
			}
		}
		return $Ids;
	}
	
	public function getOldAticleId($articleIds,$isNewId = true){
		$oldArticleIds = array();
		$str = preg_replace('/(\d+)/', '%s', implode(',', $articleIds));
		$sql="select OldPrimaryKey,PrimaryKey from DataMigrationMap where ";
		$where = " TableName = 'Article' and PrimaryKey in (".$str.")";
		if(!$isNewId){
			$where = " TableName = 'Article' and OldPrimaryKey in (".$str.")";
		}
		$result = $this->query($sql.$where, $articleIds);
		$primaryTag = array();
		while ($result->fetch_assoc()){
			$oldArticleIds[$result->getData('PrimaryKey')] = $result->getData('OldPrimaryKey');
		}
		if(!$isNewId){
			$oldArticleIds = array_flip($oldArticleIds);
		}
		return $oldArticleIds;
	}
	
	public function getNewImgId($oldImgIds){
		$newImgIdArr = array();
		$str = preg_replace('/(\d+)/', '%s', implode(',', $oldImgIds));
		$sql="select PrimaryKey from DataMigrationMap where TableName = 'ImageLibrary' and OldPrimaryKey in (".$str.")";
		$result = $this->query($sql, $oldImgIds);
		while ($result->fetch_assoc()){
			if(!in_array($result->getData('PrimaryKey'), $newImgIdArr)){
				$newImgIdArr[] = $result->getData('PrimaryKey');
			}
		}
		return $newImgIdArr;
	}
	
	public function getQueryResult($query){
		return $this->getAll($query);
	}
	
	/**
	 * **********************文章老数据通过方法 start*********************************
	 */
	/**
	 * 添加老文章
	 */
	public function addOldArticleData($articleModel) {
		$this->initOldDB ();
		//操作document_index 获取document_id(为第一个的文章ID)
		$articleModel->ArticleOldID = $this->getNewDocumentId ();
		$this->saveContentCopy ( $articleModel );
		$this->saveOldArticleContentFirst ( $articleModel );
		
		$this->initNewDB ();
		$sql = "insert into DataMigrationMap (TableName,PrimaryKey,OldPrimaryKey) ";
		$sql .= "values('".$articleModel->getTableName()."','".$articleModel->Id."','" . $articleModel->ArticleOldID . "')";
		$this->query ( $sql );
		//先修改publishid为老id
		$this->updatePublistId($articleModel->Id,$articleModel->ArticleOldID);
		$this->initOldDB ();
		if ($articleModel->SiteType == \haibao\cms\model\data\Article::SITETYPE_ARTICLE) {
			//处理另外几页文章内容
			unset ( $articleModel->ArticleContent [0] );
			if(!empty($articleModel->ArticleContent)){
				$this->saveOldArticleContentOther ( $articleModel );
			}
		}
		//文章关联产品处理
		$this->saveOldArticleProduct ( $articleModel->ArticleOldID, $articleModel->ArticleProduct );
		//文章关联标签处理
		$cateId = $this->saveOldArticleTag ( $articleModel, $articleModel->ArticleOldID );

		//文章关联图片
		$this->saveOldArticleImg ( $articleModel, $articleModel->ArticleOldID );

		//文章关联到导读图
		$this->saveOldDisRelImg($articleModel,$articleModel->ArticleOldID);
		
		//文章添加顶级标签
		$sql = "update doc_index set cateid = %s WHERE document_id=%s OR rootid=%s";
		$this->query($sql,array($cateId, $articleModel->ArticleOldID,$articleModel->ArticleOldID));
		$sql = "update rel_doc_tag set cateid = %s , rstatus = %s , rpublished = %s , rpic_num = %s,rpriority = %s ,rdataorder = %s WHERE document_id=%s";
		
		$published = $articleModel->Published;
		if($articleModel->Published == 3){
		    $published = 2;
		}
		$this->query($sql,array(
				$cateId,				
				$articleModel->Status,
				$published,
				$articleModel->PicCount,
				$articleModel->Level,
				strtotime($articleModel->PublishTime->format('Y-m-d H:i:s')),
				$articleModel->ArticleOldID
			)
		);	
		
		if($articleModel->AppColum){
			$this->addArticleToApp($articleModel,true);
		}
		
		return $articleModel;
	}
	
	public function getPublishedIds($pIds){
		$str = preg_replace('/(\d+)/', '%s', implode(',', $pIds));
		$sql = "select `PublishId` from `Article` where `PublishId` in (".$str.") and status = ".\haibao\cms\model\data\Article::STATUS_ENABLE;
		$result = $this->query($sql,$pIds);
		$res = array();
		while($result->fetch_assoc()){
			$res[] = $result->getData('PublishId');
		}
		return $res;
	}
	public function getArticleInfoByPublishId($publishId){
		$sql = "select Id,Title from Article where PublishId=%s and Published=1 limit 1";
		$result  = $this->query($sql,array($publishId))->fetch_assoc();
		return $result;
	}
	
	/**
	 * 添加文章、图集与品牌关系
	 * @param unknown_type $infoId
	 * @param unknown_type $publishTime
	 * @param unknown_type $brandTagIds
	 * @param unknown_type $infoType
	 */
	public function addInfoBrand($infoId,$publishTime,$brandTagIds,$infoType){
		$sql = "delete from InformationBrand where InfoId = %s and InfoType = %s";
		$this->query($sql,array($infoId,$infoType));
		
		if($brandTagIds){
			$tagIds = array();
			$contentArr = array();
			$sql = "insert into InformationBrand (InfoId,InfoType,BrandTagId,IsPrimaiy,PublishTime,CreateTime) values ";
			foreach($brandTagIds as $tagId=>$isPermaiyTag){
				$tagIds[] = $tagId;
				$sql .= "(%s,%s,%s,%s,%s,%s),";
				array_push ( $contentArr, $infoId );
				array_push ( $contentArr, $infoType );
				array_push ( $contentArr, $tagId );
				array_push ( $contentArr, $isPermaiyTag );
				array_push ( $contentArr, $publishTime->format('Y-m-d H:i:s') );
				array_push ( $contentArr, date('Y-m-d H:i:s',time()) );
			}
			$sql = rtrim ( $sql, ',' );
			$this->query ( $sql, $contentArr );
			
			if($tagIds){
				//修改品牌库某品牌记录的修改日期
				$sql = "update Brand set UpdateTime = '".date('Y-m-d H:i:s')."' where TagId in (".implode($tagIds, ',').")";
				$this->query ($sql);
			}
		}
	}
	
	/**
	 * 添加文章、图集与明星关系
	 * @param unknown_type $infoId
	 * @param unknown_type $publishTime
	 * @param unknown_type $starTagIds
	 * @param unknown_type $infoType
	 */
	public function addInfoStar($infoId,$publishTime,$starTagIds,$infoType){
		$sql = "delete from InformationStar where InfoId = %s and InfoType = %s";
		$this->query($sql,array($infoId,$infoType));
		
		if($starTagIds){
			$tagIds = array();
			$contentArr = array();
			$sql = "insert into InformationStar (InfoId,InfoType,StarTagId,IsPrimaiy,PublishTime,CreateTime) values ";
			foreach($starTagIds as $tagId=>$isPermaiyTag){
				$tagIds[] = $tagId;
				$sql .= "(%s,%s,%s,%s,%s,%s),";
				array_push ( $contentArr, $infoId );
				array_push ( $contentArr, $infoType );
				array_push ( $contentArr, $tagId );
				array_push ( $contentArr, $isPermaiyTag );
				array_push ( $contentArr, $publishTime->format('Y-m-d H:i:s') );
				array_push ( $contentArr, date('Y-m-d H:i:s',time()) );
			}
			$sql = rtrim ( $sql, ',' );
			$this->query ( $sql, $contentArr );
				
			if($tagIds){
				//修改明星库某明星记录的修改日期
				$sql = "update Celebrity set UpdateTime = '".date('Y-m-d H:i:s')."' where TagId in (".implode($tagIds, ',').")";
				$this->query ($sql);
			}
		}
	}
	
	/**
	 * 添加文章、图集与设计师关系
	 * @param unknown_type $infoId
	 * @param unknown_type $publishTime
	 * @param unknown_type $designerTagIds
	 * @param unknown_type $infoType
	 */
	public function addInfoDesigner($infoId,$publishTime,$designerTagIds,$infoType){
		$sql = "delete from InformationDesigner where InfoId = %s and InfoType = %s";
		$this->query($sql,array($infoId,$infoType));
		
		if($designerTagIds){
			$tagIds = array();
			$contentArr = array();
			$sql = "insert into InformationDesigner (InfoId,InfoType,DesignerTagId,IsPrimaiy,PublishTime,CreateTime) values ";
			foreach($designerTagIds as $tagId=>$isPermaiyTag){
				$tagIds[] = $tagId;
				$sql .= "(%s,%s,%s,%s,%s,%s),";
				array_push ( $contentArr, $infoId );
				array_push ( $contentArr, $infoType );
				array_push ( $contentArr, $tagId );
				array_push ( $contentArr, $isPermaiyTag );
				array_push ( $contentArr, $publishTime->format('Y-m-d H:i:s') );
				array_push ( $contentArr, date('Y-m-d H:i:s',time()) );
			}
			$sql = rtrim ( $sql, ',' );
			$this->query ( $sql, $contentArr );
		
			if($tagIds){
				//修改设计师库某设计师记录的修改日期
				$sql = "update Designer set UpdateTime = '".date('Y-m-d H:i:s')."' where TagId in (".implode($tagIds, ',').")";
				$this->query ($sql);
			}
		}
	}
	
	private function updateInfomationBrand($infoId,$infoType){
		if(!is_array($infoId)){
			$sql = "select Id,BrandTagId from InformationBrand where InfoId = %s and InfoType = %s";
			$result = $this->query($sql,array($infoId,$infoType));
			$tagIds = array();
			while($result->fetch_assoc()){
				$tagIds[] = $result->getData('BrandTagId');
			}
			if($tagIds){
				//修改品牌库某品牌记录的修改日期
				$sql = "update Brand set UpdateTime = '".date('Y-m-d H:i:s')."' where TagId in (".implode(',', $tagIds).")";
				$this->query($sql);
				
				$sqlBrand ='delete from InformationBrand where InfoId = %s and InfoType = %s';
				$this->query($sqlBrand,array($infoId,$infoType));
			}
		}elseif (is_array($infoId)){
			array_push($infoId,$infoType);
			$infoIdStr = preg_replace('/\d+/', '%s', implode(',', $infoId));
			$sql = "select BrandTagId from InformationBrand where InfoId in (".$infoIdStr.") and InfoType = %s";
			$result = $this->query($sql,$infoId);
			$tagIds = array();
			while($result->fetch_assoc()){
				$tagIds[] = $result->getData('BrandTagId');
			}
			if($tagIds){
				//修改品牌库某品牌记录的修改日期
				$sql = "update Brand set UpdateTime = '".date('Y-m-d H:i:s')."' where TagId in (".implode(',', $tagIds).")";
				$this->query($sql);
				
				$sqlBrand ='delete from InformationBrand where InfoId in ('.$infoIdStr.') and InfoType = %s';
				$this->query($sqlBrand,$infoId);
			}
		}
	}
	
	private function updateInformationStar($infoId,$infoType){
		if(!is_array($infoId)){
			$sql = "select StarTagId from InformationStar where InfoId = %s and InfoType = %s";
			$result = $this->query($sql,array($infoId,$infoType));
			$tagIds = array();
			while($result->fetch_assoc()){
				$tagIds[] = $result->getData('StarTagId');
			}
			if($tagIds){
				//修改品牌库某明星记录的修改日期
				$tagIdStr = preg_replace('/\d+/', '%s', implode(',', $tagIds));
				$sql = "update Celebrity set UpdateTime = '".date('Y-m-d H:i:s')."' where TagId in ($tagIdStr)";
				$this->query($sql,$tagIds);
				
				$sqlBrand ='delete from InformationStar where InfoId = %s and InfoType = %s';
				$this->query($sqlBrand,array($infoId,$infoType));
			}
		}elseif (is_array($infoId)){
			array_push($infoId,$infoType);
			$infoIdStr = preg_replace('/\d+/', '%s', implode(',', $infoId));
			$sql = "select StarTagId from InformationStar where InfoId in (".$infoIdStr.") and InfoType = %s";
			$result = $this->query($sql,$infoId);
			$tagIds = array();
			while($result->fetch_assoc()){
				$tagIds[] = $result->getData('StarTagId');
			}
			if($tagIds){
				//修改品牌库某明星记录的修改日期
				$sql = "update Celebrity set UpdateTime = '".date('Y-m-d H:i:s')."' where TagId in (".implode(',', $tagIds).")";
				$this->query($sql);
				
				$sqlBrand ='delete from InformationStar where InfoId in ('.$infoIdStr.') and InfoType = %s';
				$this->query($sqlBrand,$infoId);
			}
		}
	}
	
	private function updateInformationDesigner($infoId,$infoType){
		if(!is_array($infoId)){
			$sql = "select DesignerTagId from InformationDesigner where InfoId = %s and InfoType = %s";
			$result = $this->query($sql,array($infoId,$infoType));
			$tagIds = array();
			while($result->fetch_assoc()){
				$tagIds[] = $result->getData('DesignerTagId');
			}
			if($tagIds){
				//修改品牌库某设计师记录的修改日期
				$sql = "update Designer set UpdateTime = '".date('Y-m-d H:i:s')."' where TagId in (".implode(',', $tagIds).")";
				$this->query($sql);
				
				$sqlBrand ='delete from InformationDesigner where InfoId = %s and InfoType = %s';
				$this->query($sqlBrand,array($infoId,$infoType));
			}
		}elseif (is_array($infoId)){
			array_push($infoId,$infoType);
			$infoIdStr = preg_replace('/\d+/', '%s', implode(',', $infoId));
			$sql = "select DesignerTagId from InformationDesigner where InfoId in (".$infoIdStr.") and InfoType = %s";
			$result = $this->query($sql,$infoId);
			$tagIds = array();
			while($result->fetch_assoc()){
				$tagIds[] = $result->getData('DesignerTagId');
			}
			if($tagIds){
				//修改品牌库某设计师记录的修改日期
				$sql = "update Designer set UpdateTime = '".date('Y-m-d H:i:s')."' where TagId in (".implode(',', $tagIds).")";
				$this->query($sql);
				
				$sqlBrand ='delete from InformationDesigner where InfoId in ('.$infoIdStr.') and InfoType = %s';
				$this->query($sqlBrand,$infoId);
			}
		}
	}
	
	
	/**
	 * 修改老文章
	 */
	private function updateOldArticleData($articleModel) {
		// 获取老的文章ID
		$this->initNewDB();
		$sql = 'select OldPrimaryKey from DataMigrationMap where TableName = %s and PrimaryKey =%s';
		$result = $this->query($sql,array('Article',$articleModel->Id))->fetch_assoc();
		$documentId = $result['OldPrimaryKey'];
		//没有找到新-老关系对应记录
		if(empty($documentId)) return NULL;
		$articleModel->ArticleOldID=$documentId;
		$this->initOldDB ();
		$this->saveContentCopy ( $articleModel );
		$this->saveOldArticleContentFirst($articleModel, true);
		if ($articleModel->SiteType == \haibao\cms\model\data\Article::SITETYPE_ARTICLE) {
			//处理另外几页文章内容
			unset ( $articleModel->ArticleContent [0] );
			if(!empty($articleModel->ArticleContent)){
				$this->saveOldArticleContentOther ($articleModel);
			}
		}

		$this->saveOldArticleProduct ( $documentId, $articleModel->ArticleProduct );
		
		$cateId = $this->saveOldArticleTag ( $articleModel, $documentId );
		
		$this->saveOldArticleImg ( $articleModel, $documentId );
		
		$this->saveOldDisRelImg($articleModel,$documentId);
		
		//文章添加顶级标签
		$sql = "update doc_index set cateid = %s WHERE document_id=%s OR rootid=%s";
		$this->query($sql,array($cateId, $documentId,$documentId));
		
		$sql = "update rel_doc_tag set cateid = %s , rstatus = %s , rpublished = %s , rpic_num = %s,rpriority = %s ,rdataorder = %s WHERE document_id=%s";
		
		$published = $articleModel->Published;
		if($articleModel->Published == 3){
		    $published = 2;
		}
		$this->query($sql,array(
				$cateId,				
				$articleModel->Status,
				$published,
				$articleModel->PicCount,
				$articleModel->Level,
				strtotime($articleModel->PublishTime->format('Y-m-d H:i:s')),
				$articleModel->ArticleOldID
			)
		);
		if($articleModel->AppColum){
			$this->addArticleToApp($articleModel,true);
		}
		
	}

	/**
	 * 备份文章数据
	 * @param : Int $documentId 文章ID
	 * @param : Object \haibao\cms\model\data\ArticleModel
	 */
	private function saveContentCopy( $articleModel ) {			
			$sql = "INSERT INTO `haibao_article`.`content_recover` (
    		`document_id` ,
    		`content` ,
    		`date`
    		)
    		VALUES (%s,%s,%s)";
			$valArr = array ();
			array_push ( $valArr, $articleModel->ArticleOldID );
			array_push ( $valArr, $articleModel->Content );
			array_push ( $valArr,date('Y-m-d H:m:i'));
			$this->query ( $sql, $valArr );
	}
	
	/**
	 * 添加文章第一页内容（组图资讯/普通资讯）
	 * @param : Object \haibao\cms\model\data\Article
	 * @param : Int $documentId 文章父ID
	 */
	private function saveOldArticleContentFirst($articleModel,$isEdit = false) {
		$valArr = array ();
		if(!$isEdit){
			$sql = "insert into `doc_index` (`document_id`,`title`,`second_title`,`digest`,`Author`,`username`,`lastusername`,`priority`,`is_fee`,`producer_link`,`pic_source`,`article_source`,`date`,`dateorder`,`published`,`doc_type`,`sitetype`,`pic_num`) values(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)";
			array_push ( $valArr, $articleModel->ArticleOldID );
			array_push ( $valArr, $articleModel->Title );
			array_push ( $valArr, $articleModel->ShortTitle );
			array_push ( $valArr, $articleModel->Summary );
			array_push ( $valArr, \haibao\cms\business\Article::getCurrentUser()->RealName);
			array_push ( $valArr, $articleModel->Author );
			array_push ( $valArr, $articleModel->Author );
			array_push ( $valArr, $articleModel->Level);
			array_push ( $valArr, $articleModel->IsPseudonym );
			array_push ( $valArr, $articleModel->ArticleSource );
			array_push ( $valArr, '');
			array_push ( $valArr, $articleModel->ArticleSource );
			array_push ( $valArr, $articleModel->CreateTime->format( 'Y-m-d H:i:s'));
			array_push ( $valArr, $articleModel->PublishTime);
			array_push ( $valArr, $articleModel->Published );
			array_push ( $valArr, $articleModel->SiteType + 1);
			array_push ( $valArr, $articleModel->SiteType );
			array_push ( $valArr, $articleModel->PicCount );
			$this->query ( $sql, $valArr );
			if ($articleModel->SiteType == 0) {
				$content = '';
				if($articleModel->ArticleContent){
					$content = $articleModel->ArticleContent[0]->Content;
				}
				//普通文章内容入库
				$tableName = $this->createContentTable ( $articleModel->ArticleOldID );
				$sql = "insert into $tableName (document_id,content) values (%s,%s) ";
				$this->query ( $sql, array (
						$articleModel->ArticleOldID,
						$content
				) );
			} else {
				//组图文章入图片库
				$sql = "insert into content_images (document_id,content) values (%s,%s)";
				$this->query ( $sql, array (
						$articleModel->ArticleOldID,
						addslashes ( $articleModel->ArticleContent ) 
				) );
			}
			
		}else{
			$sql = 'update doc_index  set `title` = %s,`second_title` = %s,`digest` = %s,`lastusername` = %s,`priority` = %s,`is_fee` = %s,`producer_link` = %s,`pic_source` = %s,`article_source` = %s,`date` = %s,`dateorder` = %s,`published` = %s,`doc_type`= %s,`sitetype`= %s,`pic_num`= %s where document_id = %s';
			array_push ( $valArr, $articleModel->Title);
			array_push ( $valArr, $articleModel->ShortTitle );
			array_push ( $valArr, $articleModel->Summary );
			array_push ( $valArr, $articleModel->Author );
			array_push ( $valArr, $articleModel->Level);
			array_push ( $valArr, $articleModel->IsPseudonym );
			array_push ( $valArr, $articleModel->ArticleSource );
			array_push ( $valArr, '');
			array_push ( $valArr, $articleModel->ArticleSource );
			array_push ( $valArr, date('Y-m-d H:m:i'));
			array_push ( $valArr, $articleModel->PublishTime);
			array_push ( $valArr, $articleModel->Published );
			array_push ( $valArr, $articleModel->SiteType + 1);
			array_push ( $valArr, $articleModel->SiteType );
			array_push ( $valArr, $articleModel->PicCount );
			array_push ( $valArr, $articleModel->ArticleOldID );
			$this->query ( $sql, $valArr );
			
			if ($articleModel->SiteType == 0) {
			
				//普通文章内容入库
				$tableName = "content_".floor($articleModel->ArticleOldID/10000);
				$sql = "update  $tableName set  content = %s where document_id = %s";
				$this->query ( $sql, array (
						$articleModel->ArticleContent[0]->Content,
						$articleModel->ArticleOldID,
				) );
				
				//删除原有文章信息
				$sql = 'select document_id from `doc_index` where fatherid=%s and rootid=%s';
				$result = $this->query($sql,array($articleModel->ArticleOldID,$articleModel->ArticleOldID));
				$documentIdArr = array();
				while($result->fetch_assoc()){
					$documentIdArr[] = $result->getData('document_id');
					$tableName = "content_".floor($result->getData('document_id')/10000);
					$sql = "delete from $tableName where document_id = %s";
					$this->query($sql,array($result->getData('document_id')));
				}
				
				if($documentIdArr){
					$sql = 'delete from `doc_index` where fatherid=%s and rootid=%s';
					$this->query($sql,array($articleModel->ArticleOldID,$articleModel->ArticleOldID));
				}
			} else {
				//组图文章入图片库
				$sql = "update content_images set content =%s where document_id = %s";
				$this->query ( $sql, array (
						addslashes ( $articleModel->ArticleContent ),
						$articleModel->ArticleOldID,
				) );
			}
		}
	}
	/**
	 * 添加文章分页内容
	 * @param : String $content
	 * @param : Int $documentId 文章父ID
	 * @param : Object $articleModel 
	 */
	private function saveOldArticleContentOther($articleModel) {
		$valArr = array();
		$contentArr = array();
		$contentLoop=array();
		$pid=0;
		$docSql = "insert into `doc_index` (`document_id`,`title`,`digest`,`Author`,`username`,`lastusername`,`priority`,`producer_link`,`date`,`dateorder`,`published`,`doc_type`,`sitetype`,`pic_num`,`rootid`,`fatherid`) values ";
		foreach( $articleModel->ArticleContent as $key =>$Content){
			$pid = $this->getNewDocumentId ();			
			$contentTableName = $this->createContentTable ( $pid );			
			$contentLoop[$contentTableName][$pid]=$Content;
			$docSql.="(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s),";
			array_push($valArr,$pid);
			array_push($valArr,$articleModel->Title);
			array_push($valArr,$articleModel->Summary);
			array_push($valArr,$articleModel->Author);
			array_push($valArr,$articleModel->Author);
			array_push($valArr,$articleModel->Author);
			array_push($valArr,$articleModel->Level);
			array_push($valArr,$articleModel->ArticleSource);
			array_push($valArr,$articleModel->CreateTime->format( 'Y-m-d H:i:s'));
			array_push($valArr,$articleModel->PublishTime);
			array_push($valArr,0);
			array_push($valArr,$articleModel->SiteType + 1);
			array_push($valArr,$articleModel->SiteType);
			array_push ( $valArr, $articleModel->PicCount );
			array_push ( $valArr, $articleModel->ArticleOldID );
			array_push ( $valArr, $articleModel->ArticleOldID );
			
		}
		$docSql=rtrim($docSql,',');
		$this->query ( $docSql, $valArr );
			
		//普通文章内容入库,因为表名是变化的,暂时没想到更好的办法
		foreach ( $contentLoop as $key => $content ) {
			$contentSql = "insert into $key (document_id,content) values ";
			foreach ( $content as $k => $value ) {
				$contentSql .= "(%s,%s),";
				array_push ( $contentArr, $k );
				array_push ( $contentArr, $value->Content );
			}
			$contentSql = rtrim ( $contentSql, ',' );
			$this->query ( $contentSql, $contentArr );
		}
	
	}
	
	private function createContentTable($documentId) {
		$tableName = "content_" . floor ( $documentId / 10000 );
		$sql = "CREATE TABLE IF NOT EXISTS $tableName (
    	document_id int(11) DEFAULT '0' NOT NULL,
    	content mediumtext NOT NULL,
    	PRIMARY KEY (document_id))";
		$this->query ( $sql );
		return $tableName;
	}
	
	/**
	 * @param Int $documentId 文章父Id
	 * @param Array $products        	
	 */
	private function saveOldArticleProduct($documentId, $products) {
		$sql = "delete from `doc_index_product_ids` where `document_id` = %s";
		$this->query ( $sql, array (
				$documentId
		) );
		
		$productIdArr = $oldProductIdArr = array ();
		if ($products) {
			
			foreach ( $products as $product ) {
				$productIdArr [] = $product->ProductId;
			}
			$this->initNewDB();
			$sql = 'select * from `DataMigrationMap` where TableName=%s and PrimaryKey in ('.implode(',',$productIdArr).')';
			$result = $this->query($sql,array('ProductModel'));
			while($result->fetch_assoc()){
				$oldProductIdArr[$result->getData('PrimaryKey')] = $result->getData('OldPrimaryKey');
			}
			
			if($oldProductIdArr){
				$this->initOldDB();
				$sqlArr = $valArr = array ();
				$sql = "insert into `doc_index_product_ids` (`document_id`,`product_id`) values ";
				foreach ( $productIdArr as $id ) {
					if(!empty($oldProductIdArr[$id])){
						array_push ( $sqlArr, '(%s,%s)' );
						array_push ( $valArr, $documentId, $oldProductIdArr[$id] );
					}
				}			
				$sql .= implode ( ',', $sqlArr );
				$this->query ( $sql, $valArr );
			}
		}
	}
	
	private function delOldArticleTag($articleId,$tagId){
		$sql="select OldPrimaryKey from DataMigrationMap where TableName = %s and PrimaryKey = %s ";
		$articleResult = $this->query($sql,array('Article',$articleId))->fetch_assoc();
		if($articleResult){
			$this->initOldDB ();
			$sql = 'delete from rel_doc_tag where document_id=%s and tag_id=%s';
			$this->query ( $sql, array ($articleResult['OldPrimaryKey'],$tagId ));
		}
	}
	
	/**
	 * 文章关联标签处理
	 */
	private function saveOldArticleTag($articleModel, $documentId,$isAdd = true) {
		$cateId = "";
		$this->initOldDB ();
		if($isAdd){
			//删除文章原始标签
			$sql = 'delete from rel_doc_tag where document_id=%s';
			$this->query ( $sql, array ($documentId ) );
		}
		$valArr = $sqlArr = array ();
		if ($articleModel->ArticleTag) {
			$sql = 'insert into rel_doc_tag(document_id,tag_id,istpl,suser,lastmodified,rpriority,rpic_num,rdataorder,rpublished,rdoc_type,rsitetype,rstatus) values ';
			foreach ( $articleModel->ArticleTag as $tag ) {

				if($tag->TagId ){
				    $published = $articleModel->Published;
				    if($articleModel->Published == 3){
				        $published = 2;
				    }
					array_push ( $sqlArr, '(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)' );
					array_push ( $valArr, $documentId );
					array_push ( $valArr, $tag->TagId );
					array_push ( $valArr, $tag->IsPrimaiy );
					array_push ( $valArr, $articleModel->Author );
					array_push ( $valArr, time() );
					array_push ( $valArr, $articleModel->Level );
					array_push ( $valArr, $articleModel->PicCount );
					array_push ( $valArr, strtotime($articleModel->PublishTime->format('Y-m-d H:i:s')));
					array_push ( $valArr, $published );
					array_push ( $valArr, $articleModel->SiteType + 1 );
					array_push ( $valArr, $articleModel->SiteType );
					array_push ( $valArr, $articleModel->Status );
					if($tag->IsPrimaiy == 1){
						$cateId = $tag->ParentId;
					}
				}
			}
			if($valArr){
			$sql .= implode ( ',', $sqlArr );
			$this->query ( $sql, $valArr );
			}
		}
		
		//投票
		$voteNum = 0;
		$sqlArr = array();
		$valArr = array();
		$sql="select count(id) as count from vote_newvote where article_id = %s ";
		$result = $this->query ( $sql, array($documentId) );
		while($result->fetch_assoc()){
			$voteNum = $result->getData('count');
		}
		if($voteNum){
			$sql = "REPLACE into rel_doc_tag (document_id,tag_id,istpl,suser,lastmodified,rpriority,rpic_num,rdataorder,rpublished,rdoc_type,rsitetype,rstatus) 
			values ";
			
			$published = $articleModel->Published;
			if($articleModel->Published == 3){
			    $published = 2;
			}
			
			array_push ( $sqlArr, '(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)' );
			array_push ( $valArr, $documentId );
			array_push ( $valArr, '2713' );
			array_push ( $valArr, '0' );
			array_push ( $valArr, $articleModel->Author );
			array_push ( $valArr, time() );
			array_push ( $valArr, $articleModel->Level );
			array_push ( $valArr, $articleModel->PicCount );
			array_push ( $valArr, strtotime($articleModel->PublishTime->format('Y-m-d H:i:s')));
			array_push ( $valArr, $published );
			array_push ( $valArr, $articleModel->SiteType + 1 );
			array_push ( $valArr, $articleModel->SiteType );
			array_push ( $valArr, $articleModel->Status );
			$sql.=join(',',$sqlArr);
			$result = $this->query ( $sql, $valArr );
			
		}
		
		//处理无结构标签
		$sql = "select tag_id, tag_name,alias from tag where parent_id=6 and tag_status=1";
		$result = $this->query ( $sql );
		while ( $result->fetch_assoc () ) {
			
			$tagId = $result->getData ( 'tag_id' );
			$aliasStr = str_replace ( '，', ',', $result->getData ( 'alias' ) );
			$aliasArr = explode ( ',', $aliasStr );
			$aliasArr [] = $result->getData ( 'tag_name' );
			if ($aliasArr) {
				$aliasArr = array_filter ( $aliasArr );
				foreach ( $aliasArr as $key => $tagName ) {
					if (strpos ( $articleModel->Title, $tagName ) !== false) {
						$sql = "select document_id from `rel_doc_tag` where document_id=%s and tag_id=%s";
						$data = $this->query ( $sql, array (
								$documentId,
								$tagId 
						) )->fetch_assoc ();
						
						if (! $data) {
							$sql = 'replace into rel_doc_tag(document_id,tag_id,istpl,suser,lastmodified,rpriority,rpic_num,rdataorder,rpublished,rdoc_type,rsitetype,rstatus) values (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)';
							
							$published = $articleModel->Published;
							if($articleModel->Published == 3){
							    $published = 2;
							}
							
							$this->query ( $sql, 
								array (
									$documentId,
									$tagId,
									0,
									$articleModel->Author,
									strtotime($articleModel->CreateTime->format('Y-m-d H:i:s')) ,
									$articleModel->Level,
									$articleModel->PicCount,
									strtotime($articleModel->PublishTime->format('Y-m-d H:i:s')),
									$published,
									$articleModel->SiteType + 1,
									$articleModel->SiteType,
									$articleModel->Status
								)
							);
						}
					}
				}
			}
		}
		return $cateId;
	}
	
	/**
	 * 添加到文章关联系事件表
	 * @param 文章关联事件的实体 $articleEventModel
	 * @param 文章id $articleId
	 */
	private function addEventArticle($articleEventModel,$articleId){
		$sql="delete from EventArticle where ArticleId = %s ";
		$this->query($sql,array($articleId));
		if($articleId && !empty($articleEventModel) && $articleEventModel->EventId){
			$articleEventModel->ArticleId = $articleId;
			$this->add($articleEventModel);
		}
	}
	
	
	/**
	 * 文章关联图片
	 * @param : Object \haibao\cms\model\data\Article
	 * @param : Int $documentId
	 * @table : content_photo
	 */
	private function saveOldArticleImg($articleModel, $documentId) {
		if(empty($articleModel->ArticleImage)) return "";
		$articleImages = $this->getImageRel($articleModel->ArticleImage);
		$articleModel->ArticleOldImageId=$articleImages;
		$this->initOldDB();
		$sql = 'delete from `content_photo` where article_id = %s and disrel = 0';
		$this->query ( $sql, array ($documentId) );
		if($articleImages){
			$valArr = $sqlArr = array ();
			$sql = "INSERT INTO `content_photo` (`image`,`date`,`article_id`,`title`,`blog_id`,`origin_url`,`pic_id`,`width`,`height`,`sitetype`) VALUES ";
			foreach ( $articleImages as $key => $image ) {
				$descriptionStr = $image->Description;
				if(empty($descriptionStr)){
					$descriptionStr = $this->getPicDes($image->ImageId);
				}
				array_push ( $sqlArr, '(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)');
				array_push ( $valArr, ltrim($image->PicUrl, '/') );
				array_push ( $valArr, date ( 'Y-m-d H:i:s' ) );
				array_push ( $valArr, $documentId );
				array_push ( $valArr, $descriptionStr );
				array_push ( $valArr, 0 );
				array_push ( $valArr, ltrim($image->PicUrl, '/') );
				array_push ( $valArr, (string)$image->ImageId );
				array_push ( $valArr, $image->Width );
				array_push ( $valArr, $image->Height );
				array_push ( $valArr, $articleModel->SiteType );
			}
			$sql .=implode(',',$sqlArr);
			$this->query ( $sql, $valArr );
		}
		
		$sql = 'DELETE FROM `picsm_pic_obj` WHERE `obj_id` = %s and `disrel` = 0 ';
		$this->query ( $sql, array ($documentId ) );
		
		if($articleImages){
			$imageArr = $sqlArr = $valArr = array();
			$sql = "INSERT INTO `picsm_pic_obj` (`module_id` ,`obj_id` ,`pic_id`,`disrel`,`adddate`,`is_order`) VALUES ";
			foreach ( $articleImages as $key => $image ) {
				if(!in_array($image->ImageId, $imageArr)){//图片去重
					array_push ( $sqlArr, '(%s,%s,%s,%s,%s,%s)');
					array_push ( $valArr, 1 );
					array_push ( $valArr, $documentId );
					array_push ( $valArr, $image->ImageId );
					array_push ( $valArr, 0 );
					array_push ( $valArr, date ( 'Y-m-d H:i:s' ) );
					array_push ( $valArr, $key + 1 );
					$imageArr[]=	$image->ImageId;
				}
			}
			$sql .= implode(',',$sqlArr);
			$this->query ( $sql, $valArr );
		}
	}
	
	private function getPicDes($picId){
		$decStr = '';
		$sql = 'select description FROM `picsm_pic_info` WHERE `pic_id` = '.$picId.' limit 1';
		$result = $this->query($sql);
		while($result->fetch_assoc()){
			$decStr = $result->getData ( 'description' );
			break;
		}
		return $decStr;
	}
	
	/**
	 * 文章添加导读图
	 */
	private function saveOldDisRelImg($articleModel,$documentId){
		$articleImages = $this->getImageRel($articleModel->ArticleProImage);
		
		$this->initOldDB();
		$sql = 'delete from `content_photo` where article_id = %s and disrel > 0 and disrel < 10';
		$this->query($sql,array($documentId));
		
		if($articleImages){
			$imageArr = $valArr = $sqlArr = array();
			$sql = "INSERT INTO `content_photo` (`image`,`date`,`article_id`,`title`,`origin_url`,`pic_id`,`width`,`height`,`disrel`,`sitetype`) VALUES ";
			foreach($articleImages as $key=>$image){
				array_push($sqlArr, ' (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)');
				array_push ( $valArr, ltrim($image->PicUrl, '/') );
				array_push ( $valArr, date ( 'Y-m-d H:i:s' ) );
				array_push ( $valArr, $documentId );
				array_push ( $valArr, $image->Description );
				array_push ( $valArr, ltrim($image->PicUrl, '/') );
				array_push ( $valArr, $image->ImageId );
				array_push ( $valArr, $image->Width );
				array_push ( $valArr, $image->Height );
					
				if($image->PicType == \haibao\cms\model\data\ArticleProImage::PIC_TYPE_INTRO){
					if($image->Level == \haibao\cms\model\data\ArticleProImage::Level_ZERO){
						array_push ( $valArr, \haibao\cms\model\data\ArticleProImage::OLD_SET_PRO_IMG_TYPE );
					}elseif($image->Level == \haibao\cms\model\data\ArticleProImage::Level_FIVE){
						array_push ( $valArr, \haibao\cms\model\data\ArticleProImage::OLD_UPLOAD_PRO_IMG_4_3 );
					}elseif($image->Level == \haibao\cms\model\data\ArticleProImage::Level_FOUR){
						array_push ( $valArr, \haibao\cms\model\data\ArticleProImage::OLD_UPLOAD_PRO_IMG_1_1 );
					}else{
						array_push ( $valArr, \haibao\cms\model\data\ArticleProImage::OLD_UPLOAD_PRO_IMG_5_7 );
					}
				}elseif($image->PicType == \haibao\cms\model\data\ArticleProImage::PIC_TYPE_COVER){
					array_push ( $valArr, 2 );
				}
				array_push ( $valArr, $articleModel->SiteType );
			}
			$sql .= implode(',',$sqlArr);
			$this->query ( $sql, $valArr );
		} else {
			$sql = 'delete from `content_photo` where article_id = %s';
			$this->query($sql,array($documentId));
		}
		
		
		$sql = 'DELETE FROM `picsm_pic_obj` WHERE `obj_id` = %s and disrel > 0 and disrel < 10';
		$this->query($sql,array($documentId));
		
		if($articleImages){
			$sql = "INSERT INTO `picsm_pic_obj` (`module_id` ,`obj_id` ,`pic_id`,`disrel`,`adddate`,`is_order`) VALUES ";
			$valArr = $sqlArr = array();
			foreach($articleImages as $key=>$image){
			
				if(!in_array($image->ImageId, $imageArr)){//鍥剧墖鍘婚噸
					array_push($sqlArr, '(%s,%s,%s,%s,%s,%s)');
					array_push ( $valArr, 1 );
					array_push ( $valArr, $documentId );
					array_push ( $valArr, $image->ImageId );
			
					
					if($image->PicType == \haibao\cms\model\data\ArticleProImage::PIC_TYPE_INTRO){
						if($image->Level == \haibao\cms\model\data\ArticleProImage::Level_ZERO){
							array_push ( $valArr, \haibao\cms\model\data\ArticleProImage::OLD_SET_PRO_IMG_TYPE );
						}elseif($image->Level == \haibao\cms\model\data\ArticleProImage::Level_FIVE){
							array_push ( $valArr, \haibao\cms\model\data\ArticleProImage::OLD_UPLOAD_PRO_IMG_4_3 );
						}elseif($image->Level == \haibao\cms\model\data\ArticleProImage::Level_FOUR){
							array_push ( $valArr, \haibao\cms\model\data\ArticleProImage::OLD_UPLOAD_PRO_IMG_1_1 );
						}else{
							array_push ( $valArr, \haibao\cms\model\data\ArticleProImage::OLD_UPLOAD_PRO_IMG_5_7 );
						}
					}elseif($image->PicType == \haibao\cms\model\data\ArticleProImage::PIC_TYPE_COVER){
						array_push ( $valArr, 2 );
					}
					
					/* if($image->PicType == \haibao\cms\model\data\ArticleProImage::PIC_TYPE_INTRO){
						if($image->Level == \haibao\cms\model\data\ArticleProImage::Level_ZERO){
							array_push ( $valArr, \haibao\cms\model\data\ArticleProImage::OLD_SET_PRO_IMG_TYPE );
						}elseif($image->Level == \haibao\cms\model\data\ArticleProImage::Level_ONE){
							array_push ( $valArr, \haibao\cms\model\data\ArticleProImage::OLD_UPLOAD_PRO_IMG_4_3 );
						}elseif($image->Level == \haibao\cms\model\data\ArticleProImage::Level_TWO){
							array_push ( $valArr, \haibao\cms\model\data\ArticleProImage::OLD_UPLOAD_PRO_IMG_1_1 );
						}else{
							array_push ( $valArr, \haibao\cms\model\data\ArticleProImage::OLD_UPLOAD_PRO_IMG_5_7 );
						}
					}elseif($image->PicType == \haibao\cms\model\data\ArticleProImage::PIC_TYPE_COVER){
						array_push ( $valArr, 2 );
					} */
			
					array_push ( $valArr, date ( 'Y-m-d H:i:s' ) );
					array_push ( $valArr, $key+1 );
					$imageArr[] = $image->ImageId;
				}
			}
			$sql .= implode(',',$sqlArr);
			$this->query ( $sql, $valArr );
		} else {
			$sql = 'DELETE FROM `picsm_pic_obj` WHERE `obj_id` = %s';
			$this->query($sql,array($documentId));
		}
		
	}
	
	/**
	 * 给新加的图片添加跟老图一样的图片标签 (新图跟老图同一个ID 自增长ID不同)
	 * @param Int $picId 图片ID
	 * @param Int $contentPhotoId content_photo 自增长ID
	 * @param Int $documentId 文章ID
	 */
	private function addPicTag($documentId = 0) {
		$picIdArr=array();
		$contentPhotoIdArr=array();
		$dbPhotoIdArr = array();	
		$picIds='';
		$contentPhotoIds='';
		$dbPhotoIds='';
		$i=0;
		$tagsArr = array();
		$sql="select pic_id,id from content_photo where article_id  = %s ";
		$result = $this->query($sql,array($documentId));
		while($result->fetch_assoc()){
			$picIdArr[] = $result->getData ( 'pic_id' );
			$contentPhotoIdArr[] = $result->getData ( 'id' );
		}
		
	
		// 查出相同pic_id的content_photo_id
		if($picIdArr) $picIds = join(',', $picIdArr);
		if($contentPhotoIdArr) $contentPhotoIds = join(',', $contentPhotoIdArr);
		$sql = "select id from content_photo where pic_id = %s and id <> %s order by id limit 1";
		$result = $this->query ( $sql,array($picIds[0],$contentPhotoIds[0]));
		while ( $result->fetch_assoc () ) {
			$dbPhotoIdArr[] = $result->getData ( 'id' );
		}
		if ($dbPhotoIdArr ) {
			$dbPhotoIds = $dbPhotoIdArr[0];
			$sql = "select photo_id,articleclass_id,istpl from content_photo_tags where photo_id in ( %s )";
			$r = $this->query ( $sql, array ($dbPhotoIds) );			
			while ( $r->fetch_assoc () ) {
				$tagsArr[]['photo_id']=$r->getData('photo_id');
				$tagsArr[]['articleclass_id']=$r->getData('articleclass_id');
				$tagsArr[]['istpl']=$r->getData('istpl');				
			}
			if($tagsArr){
				$sql="insert into `content_photo_tags` (`photo_id`,`articleclass_id`,`document_id`,`istpl`,`pic_id`) values ";
				foreach ( $tagsArr as $key => $tags ) {
					array_push($sqlval,  '(%s,%s,%s,%s,%s)');
					array_push($array, $tags['photo_id']);
					array_push($array, $tags['articleclass_id']);
					array_push($array, $documentId);
					array_push($array, $tags['istpl']);
					array_push($array, $picIds[0]);
				}
				$insertTag=$this->query($sql,$array);
			}
			
		}
	}
	
	/**
	 * 删除文章图片信息
	 * @param : $documentId 文章ID
	 */
	private function deleteOldArticleImg($documentId) {
		$sql = "DELETE FROM `content_photo` WHERE `article_id` = %s and `disrel` = 0 ";
		$this->query ( $sql, array ($documentId ) );
		
		$sql = "select pic_id from `picsm_pic_obj` WHERE `obj_id` = %s and `disrel` = 0 ";
		$result = $this->query ( $sql, array ($documentId ) );
		$picIdArr = array ();
		while ( $result->fetch_assoc () ) {
			$picIdArr [] = $result->getData ( 'pic_id' );
		}
		
		if ($picIdArr) {
			$sql = "DELETE FROM `picsm_pic_index` where pic_id in (" . implode ( ",", $picIdArr ) . ")";
			$this->query ( $sql );
		}
		
		$sql = "DELETE FROM `picsm_pic_obj` WHERE `obj_id` = %s and `disrel` = 0 ";
		$this->query ( $sql, array ($documentId ) );
	}
	
	// 标签补丁
	private function modifyPicTag($picId, $contentPhotoId, $documentId = 0) {
		$sql = "select * from `content_photo_tags` where pic_id = %s and `photo_id` = 0 order by id limit 1";
		$result = $this->query ( $sql, array ($picId ) )->fetch_assoc ();
		if ($result) {
			$sql = "update `content_photo_tags` set `photo_id`=%s where pic_id = %s and `photo_id` = 0 ";
			$this->query ( $sql, array ($contentPhotoId,$picId ) );
		}
	}
	
	/**
	 * 取得最新的符合规范的文章ID
	 */
	private function getNewDocumentId() {
		$sql = "select max(document_id) as documentId from doc_index";
		$result = $this->query ( $sql );
		while ( $result->fetch_assoc () ) {
			
			$maxId = $result->getData ( 'documentId' );
		}
		$id = $this->createDocumentId ();
		while ( $id < $maxId + 1 ) {
			$id = $this->createDocumentId ();
		}
		return $id;
	}
	
	/**
	 * 生成一个新的文章ID
	 */
	private function createDocumentId() {
		$sql = "insert into document_index (class_id) values ('0')";
		$this->query ( $sql );
		return $this->getDb ()->insert_id;
	}
	

	private function initNewDB() {
		$this->setConfig( \haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_MYSQL_HAIBAO_CMS );
		return $this;
	}
	private function initOldDB() {
		$this->setConfig( \haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_MYSQL_HAIBAO_ARTICLE );
		return $this;
	}
	
	/**
	 * 取得媒体报道中日期数据的缓存数据
	 */
	public function getReportDateCache(){
		$cache = new \haibao\cms\cache\ReportDate();
		$dateArr = $cache->getReportDate();
		if(empty($dateArr)){
			$getDateArr = $this->getReportDateArr();
			$cache->setReportDate($getDateArr);
			return $getDateArr;
		}else{
			return $dateArr;
		}
	}
	
	/**
	 * 设置PIC点击数
	 */
	public function updatePicClickNum($articleId){
	    $this->dealArticleClickNumData($articleId,self::ARTICLE_CLICK,false,true,true);
	    
	    $this->addInfoClickNumData($articleId,1);
// 	    $sql = "update ArticleProperty set ClickNum=ClickNum+1,PicClickNum=PicClickNum+1  where ArticleId=%s";
// 	    $result  = $this->query($sql,array($articleId));
	}
	
	public function addInfoClickNumData($infoId,$infoType){
	    $dataList = array();
	    $dataList['infoId'] = $infoId;
	    $dataList['infoType'] = $infoType;
	    $dataList['time'] = time();
	    $cacheData = new \haibao\cms\cache\Article();
	    $cacheData->setArticleClickNum($dataList);
	}
	
	/**
	 * 取得媒体报道的日期分类
	 */
    public function getReportDateArr(){
		$idArr = implode($this->getIdArr(),",");
		$sql = "SELECT YEAR(CreateTime) AS `year`, MONTH(CreateTime) AS `month` FROM Article where id in (".$idArr.") GROUP BY YEAR(CreateTime), MONTH(CreateTime) ORDER BY CreateTime DESC";
		$result = $this->query($sql);
		$dateArr = array();
		$counter = 0;
		while($result->fetch_assoc()){
			$month = strlen($result->getData('month'))==1?'0'.$result->getData('month'):$result->getData('month');
			$dateArr[$counter]['list'] = $result->getData('year').'年'.$month.'月';
			$dateArr[$counter]['href'] = $result->getData('year').'-'.$month;
			$counter++;
		}
		return $dateArr;
	}
	
	/**
	 * 取得媒体报道的全部Id
	 */
	private function getIdArr(){
		$articleFilter = new \haibao\cms\model\filter\Article();
		$articleTagFilter = new \haibao\cms\model\filter\ArticleTag();
		$articleFilter->select(array(ArticleFilter::CONDITION_FIELD_NAME_ID));
		$articleTagFilter->select(array(\haibao\cms\model\filter\ArticleTag::CONDITION_FIELD_NAME_ARTICLE_ID));
		$articleFilter->leftJoin($articleTagFilter,null,\haibao\cms\model\filter\Article::CONDITION_FIELD_NAME_ID,\haibao\cms\model\filter\ArticleTag::CONDITION_FIELD_NAME_ARTICLE_ID,ArticleFilter::CONDITION_FIELD_NAME_ARTICLE_TAG,null);
		$articleTagFilter->where(\haibao\cms\model\filter\ArticleTag::CONDITION_FIELD_NAME_TAG_ID,Condition::CONDITION_EQUAL,\haibao\cms\model\data\Articletag::REPORT_TAG);
		$articleFilter->order(\haibao\cms\model\filter\Article::CONDITION_FIELD_NAME_PUBLISHTIME,false);
		$result =  $this->getAll($articleFilter);
		$dateArr = array();
		foreach ($result as $key=>$list){
			$dateArr[] =$list->Id;
		}
		return $dateArr;
	}
	
	/**
	 * 获取图片新老数据关联关系
	 * @param : $articleImages 文章图片
	 */
	private function getImageRel($articleImages){
		if(!$articleImages) return "";
		$imageIdRel=$imageIdArr = $contentImgArr = array();
		foreach($articleImages as $img){
			$imageIdArr[] = $img->ImageId;
		}
		$imageIdArrs = array_unique($imageIdArr);
		if($imageIdArrs){
			// 查询出老库的图片Id
			$this->initNewDB();
			$sql = 'select PrimaryKey,OldPrimaryKey from DataMigrationMap where TableName = %s and PrimaryKey in ('.implode(',',$imageIdArr).')';
			$result = $this->query($sql,array('ImageLibrary'));
			while ($result->fetch_assoc()){
				$imageIdRel[$result->getData('PrimaryKey')] = $result->getData('OldPrimaryKey');
			}
			if($articleImages && $imageIdRel){
				foreach ($articleImages as $key => $image ) {
					if(!empty($imageIdRel [$image->ImageId])){
						$image->ImageId = $imageIdRel [$image->ImageId];
					}
					$contentImgArr [] = $image;
				}
			} elseif($articleImages){
				foreach ($articleImages as $key => $image ) {
					$contentImgArr [] = $image;
				}
			}
		}
			
		return 	$contentImgArr;	
	}
	/**
	 * 修改老文章状态
	 */
	private function updateOldArticleStatus($articleId, $status) {
		$articleModel = new \haibao\cms\model\data\Article ();
		$tableName = $articleModel->getTableName ();
		$sql = 'select OldPrimaryKey from DataMigrationMap where TableName="' . $tableName . '" and PrimaryKey =%s';
		$result = $this->query ( $sql, array (
				$articleId 
		) );
		$oldArticleId = 0;
		while ( $result->fetch_assoc () ) {
			$oldArticleId = $result->getData ( 'OldPrimaryKey' );
		}
		if ($oldArticleId) {
			$this->setConfig( \haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_MYSQL_HAIBAO_ARTICLE );
			
			$sql = 'update doc_index set status=%s where document_id=%s or rootid=%s';
			$arrValues = array (
					$status,
					$oldArticleId,
					$oldArticleId 
			);
			$this->query ( $sql, $arrValues );
			
			// 暂时先改成0，暂不考虑两篇一样的同步到旧库中删除一篇的情况
			$sql='update rel_doc_tag set rstatus = %s where document_id=%s ';
			$arrValues = array (
					0,
					$oldArticleId
			);
			$this->query ( $sql, $arrValues );
		}
	}
	
	/**
	 * 修改老后台文章的发布状态
	 * @param unknown $articleId
	 * @param unknown $status
	 */
	private function updateOldArticlePublish($articleId, $status) {
		$articleModel = new \haibao\cms\model\data\Article ();
		$tableName = $articleModel->getTableName ();
		$articleIdArr = array();
		$sql = 'select OldPrimaryKey from DataMigrationMap where TableName="' . $tableName . '"';
		if(is_int($articleId)){
			$sql = $sql." and PrimaryKey =%s";
			$articleIdArr = array($articleId);
		}elseif(is_array($articleId)){
			$Ids = join(',',$articleId);
			$sql = $sql . "and PrimaryKey in (".$Ids.")";		
		}
		$result = $this->query ( $sql, $articleIdArr );
		
		$oldArticleId = array();
		$oldArticleIds = "";
		while ( $result->fetch_assoc () ) {
			$oldArticleId[] = $result->getData ( 'OldPrimaryKey' );
		}
		if ($oldArticleId) {
			$this->setConfig( \haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_MYSQL_HAIBAO_ARTICLE );
			$oldArticleIds = join(',',$oldArticleId);
			$sql = "update doc_index set published='".$status."' where document_id in (".$oldArticleIds.") or rootid in (".$oldArticleIds.")";
			$arrValues = array ();
			$this->query ( $sql, $arrValues );
			
			$sql = "update rel_doc_tag set rstatus = 0, rpublished = 1 WHERE document_id in (".$oldArticleIds.")";
			$this->query ( $sql );
		}
	}
	
	private function updateOldArticleLevel($articleId, $level) {
		$articleModel = new \haibao\cms\model\data\Article ();
		$tableName = $articleModel->getTableName ();
		$sql = 'select OldPrimaryKey from DataMigrationMap where TableName="' . $tableName . '" and PrimaryKey =%s';
		$result = $this->query ( $sql, array (
				$articleId 
		) );
		$oldArticleId = 0;
		while ( $result->fetch_assoc () ) {
			$oldArticleId = $result->getData ( 'OldPrimaryKey' );
		}
		if ($oldArticleId) {
			$this->setConfig( \haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_MYSQL_HAIBAO_ARTICLE );
			
			$sql = 'update doc_index set priority=%s where document_id=%s or rootid=%s';
			$arrValues = array (
					$level,
					$oldArticleId,
					$oldArticleId 
			);
			$this->query ( $sql, $arrValues );
			
			$sql='update rel_doc_tag set rpriority = %s where document_id=%s ';
			$arrValues = array (
					$level,
					$oldArticleId
			);
			$this->query ( $sql, $arrValues );
		}
	}
	
	/**
	 * 从文章推送到app
	 * @param 文章实体 $articleModel object
	 * @param 表类型 $tableType bool
	 */
	private function addArticleToApp($articleModel,$isInsertOld = false){
		$imageModels = array();
		$imageIds = array();
		$articleId = 0;	
		if($isInsertOld){
			$this->initOldDB();
			$articleId = $articleModel->ArticleOldID;
			$imageModels = $articleModel->ArticleOldImageId;
		}else{
			$this->initNewDB();
			$articleId = $articleModel->Id;
			$imageModels = $articleModel->ArticleImage;
		}
		
		if($articleId && $imageModels){
			foreach($imageModels as $key => $imageModel){
				if(!in_array($imageModel->ImageId, $imageIds) && $imageModel->ImageId){
					$imageIds[] = $imageModel->ImageId;
				}
			}
			
			$datetime = new \DateTime();
			$phoneArticleTagsModel= new \haibao\cms\model\data\PhoneArticleTags();
			$phoneArticleTagsModel->app_tag = $articleModel->AppColum;
			$phoneArticleTagsModel->create_date = $datetime->format('Y-m-d H:i:s');
			$phoneArticleTagsModel->document_id = $articleId;
			$phoneArticleTagsModel->orderdate = $articleModel->PublishTime?$articleModel->PublishTime:$datetime->format('Y-m-d H:i:s');
			$this->addPhoneArtcileTags($phoneArticleTagsModel,$isInsertOld);
			
			$AppColum = array_intersect(array(1,2,3,4,5,6,7),$articleModel->AppColum);
			if($AppColum){
				$appArticleModel = new \haibao\cms\model\data\AppArticle();
				$appArticleModel->document_id=$articleId;
				$appArticleModel->title=$articleModel->Title;
				$appArticleModel->priority=$articleModel->Level;
				if($imageIds){
					$appArticleModel->pic_id = join(',',$imageIds);
					$appArticleModel->fm_pic_id = $imageIds[0];
				}
				$appArticleModel->is_push=1;
				$appArticleModel->pub_status=$articleModel->Published;
				$appArticleModel->visit_nums=0;
				$appArticleModel->create_time= $datetime->format('Y-m-d H:i:s');
				$appArticleModel->pub_time=$articleModel->PublishTime?$articleModel->PublishTime:$datetime->format('Y-m-d H:i:s');
				$appArticleModel->pub_user=$articleModel->Author;
				$this->addAppArticle($appArticleModel,$isInsertOld);
			}
			
			$AppColum = array_intersect(array('98','99'),$articleModel->AppColum);
			
			if($AppColum){
				$phoneSpecialModel=array();
				foreach($AppColum as $key => $value){
					$phoneSpecialModel = new \haibao\cms\model\data\PhoneSpecial();
					if($value=='98'){
						$phoneSpecialModel->spec_type=$phoneSpecialModel::SPEC_TYPE_WEBVIEW;
					}elseif($value=='99'){
						$phoneSpecialModel->spec_type=$phoneSpecialModel::SPEC_TYPE_MASONRY;
					}
					$phoneSpecialModel->spec_title=$articleModel->Title;
					$phoneSpecialModel->spec_desc=$articleModel->Content;
					$phoneSpecialModel->spec_pushed=1;
					$phoneSpecialModel->spec_createtime=$datetime->format('Y-m-d H:i:s');
					$phoneSpecialModel->spec_uptime=$datetime->format('Y-m-d H:i:s');
					$phoneSpecialModel->dateorder=$datetime->format('Y-m-d H:i:s');
					$phoneSpecialModel->visit_nums=0;
					if($imageIds){
						$phoneSpecialModel->pic_id=join(',',$imageIds);
					}
					$phoneSpecialModel->spec_pusedtime=$articleModel->PublishTime?$articleModel->PublishTime:$datetime->format('Y-m-d H:i:s');
					$phoneSpecialModel->spec_article=$articleId;
					$phoneSpecialModel->create_user=$articleModel->Author;
					$phoneSpecialModel->update_user=$articleModel->Author;
					$phoneSpecialModel->pushed_user=$articleModel->Author;
					$phoneSpecialModels[]=$phoneSpecialModel;
				}
				$this->addAppSpecial($phoneSpecialModels,$isInsertOld);
			}
			$this->addAppArticleCategory($articleModel->AppColum,$articleId,$isInsertOld);
			
		}
	}
	
	
	/** 
	 * 推送文章到2.0版本app的phone_article_tags表
	 * @param phone_article_tags的实体 $model object
	 */
	private function addPhoneArtcileTags($model,$isInsertOld){
		if(!$isInsertOld){
			$tableName='PhoneArticleTags';
		}else{
			$tableName='phone_article_tags';
		}
		$sql="delete from ".$tableName." where document_id=".$model->document_id."";
		$this->query($sql);
		$sql="insert into ".$tableName." (`document_id`,`app_tag`,`orderdate`,`create_date`) values ";
		$valArr=array();
		foreach($model->app_tag as $key => $value){
			$sql .= "(%s,%s,%s,%s),";
			array_push($valArr, $model->document_id);
			array_push($valArr, $value);
			array_push($valArr, $model->orderdate);
			array_push($valArr, $model->create_date);
		}
		$sql=rtrim($sql,',');
		$this->query($sql,$valArr);
	}
	
	/**
	 * 推送文章到app_article表
	 * @param app_article的实体 $model object
	 */
	private function addAppArticle($model,$isInsertOld){
		$tableName = "";
		if($isInsertOld){
			$tableName='app_article';
		}else{
			$tableName='AppArticle';
		}
		$sql="select count(*) as count from ".$tableName." where document_id=".$model->document_id." ";
		$result=$this->query($sql);
		while ( $result->fetch_assoc () ) {
			$count = $result->getData ( 'count' );
		}
		
		if ($count == 0) {
			$sql = "INSERT INTO `" . $tableName . "` (
						document_id,
						title,
						priority,
						pic_id,
						fm_pic_id,
						is_push,
						pub_status,
						pub_time,
						pub_user,
						visit_nums,
						create_time,
						create_user
					) 
					values 
					('" . $model->document_id . "',
					 '" . $model->title . "',
					 '" . $model->priority . "',
					 '" . $model->pic_id . "',
					 '" . $model->fm_pic_id . "',
					 '" . $model->is_push . "',
					 '" . $model->pub_status . "',
					 '" . $model->pub_time->format('Y-m-d H:i:s'). "',
					 '" . $model->pub_user . "',
					 '" . $model->visit_nums . "',
					 '" . $model->create_time . "',
					 '" . $model->create_user . "')";
		} else {
			$sql = "update `" . $tableName . "` set 						
						title = '" . $model->title . "',
						priority = '" . $model->priority . "',
						pic_id = '" . $model->pic_id . "',
						fm_pic_id = '" . $model->fm_pic_id . "',
						is_push = '" . $model->is_push . "',
						pub_status = '" . $model->pub_status . "',
						pub_time = '" . $model->pub_time->format('Y-m-d H:i:s') . "',
						pub_user = '" . $model->pub_user . "'											
					where
						document_id = '" . $model->document_id . "'																					
					";
		}		
		$this->query($sql);
	}
	/**
	 * 推送文章到phone_special表
	 * @param phone_special的实体 $model array(object);
	 */
	private function addAppSpecial($model,$isInsertOld){
		$valArr =array();
		if($isInsertOld){
			$tableName='phone_special';
		}else{
			$tableName='PhoneSpecial';
		}
		foreach($model as $key => $value){
			$articleId=$value->spec_article;
		}
		$sql="select count(*) as count from ".$tableName." where spec_article = ".$articleId."  ";
		$result=$this->query($sql);	
		while ( $result->fetch_assoc () ) {
			$count = $result->getData ( 'count' );
		}
		if($count==0){
			$sql="INSERT INTO `" . $tableName . "` (
							spec_type,
							spec_title,
							spec_desc,
							spec_pushed,
							spec_createtime,
							spec_uptime,
							spec_pusedtime,
							spec_article,
							create_user,
							update_user,
							pushed_user,
							pic_id
						) values";
			foreach ($model as $key => $obj){
				$sql .= "(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s),";
				array_push($valArr, $obj->spec_type);
				array_push($valArr, $obj->spec_title);
				array_push($valArr, $obj->spec_desc);
				array_push($valArr, $obj->spec_pushed);
				array_push($valArr, $obj->spec_createtime);
				array_push($valArr, $obj->spec_uptime);
				array_push($valArr, $obj->spec_pusedtime);
				array_push($valArr, $obj->spec_article);
				array_push($valArr, $obj->create_user);
				array_push($valArr, $obj->update_user);
				array_push($valArr, $obj->pushed_user);	
				array_push($valArr, $obj->pic_id);	
			}
			$sql=rtrim($sql,',');
			$this->query($sql,$valArr);
		}
				
	}
	
	/**
	 * 推送类型与推送记录关系表
	 * @param 类型 $appColumn array
	 * @param 文章id $articleId
	 */
	private function addAppArticleCategory($appColumn,$articleId,$isInsertOld){
		if(!$isInsertOld){
			$tableName='AppArticleCategory';
		}else{
			$tableName='app_article_category';
		}
		$sql="delete from ".$tableName." where document_id='".$articleId."' ";
		$this->query($sql);	
		$sql="INSERT INTO `".$tableName."` (document_id,column_id) values ";
		$valArr = array();
		foreach($appColumn as $key => $value){
			$sql .= "(%s,%s),";
			array_push($valArr, $articleId);
			array_push($valArr, $value);
		}
		$sql=rtrim($sql,',');
		$this->query($sql,$valArr);
	} 
	
	/**
	 * 
	 */
	private function getAppPublishType(){
		
	}
	
	/**
	 * 修改老文章审核状态
	 */
	private function updateOldArticleAuditType() {
	}
	

	private function updateOldArticleEditClickNum($articleId,$num){
		$sql = 'select OldPrimaryKey from DataMigrationMap where TableName="Article" and PrimaryKey =%s';
		$result = $this->query ( $sql, array ($articleId) );
		$oldArticleId = 0;
		while ( $result->fetch_assoc () ) {
			$oldArticleId = $result->getData ( 'OldPrimaryKey' );
		}
		if ($oldArticleId) {
			$this->setConfig( \haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_MYSQL_HAIBAO_ARTICLE );
			$sql = 'update doc_index set udtgrandid=%s where document_id=%s';
			$this->query ( $sql, array($num,$oldArticleId) );
		}
	}
	
	/**
	 * 设置老文章图片的导读图/封面图
	 */
	private function setOldImageType($articleId,$imageInfo,$imgType,$level){
		
		$sql="select OldPrimaryKey from DataMigrationMap where TableName = %s and PrimaryKey = %s ";
		$articleResult = $this->query($sql,array('Article',$articleId))->fetch_assoc();
		
		$sql = 'select PrimaryKey,OldPrimaryKey from DataMigrationMap where TableName = %s and PrimaryKey = %s';
		$imageResult = $this->query($sql,array('ImageLibrary',$imageInfo->Id))->fetch_assoc();
		if($articleResult && $imageResult){

			$this->initOldDB();
			$disrel = \haibao\cms\model\data\ArticleProImage::Level_ZERO;
			if($level == \haibao\cms\model\data\ArticleProImage::Level_ZERO){
				if($imgType == \haibao\cms\model\data\ArticleProImage::PIC_TYPE_INTRO){
					$disrel = \haibao\cms\model\data\ArticleProImage::OLD_SET_PRO_IMG_TYPE;
				}else{
					$disrel = \haibao\cms\model\data\ArticleProImage::OLD_SET_COVER_IMG_TYPE;
				}
			}else if($level == \haibao\cms\model\data\ArticleProImage::Level_ONE){

				$disrel = \haibao\cms\model\data\ArticleProImage::OLD_UPLOAD_PRO_IMG_4_3;
			}else if($level == \haibao\cms\model\data\ArticleProImage::Level_TWO){

				$disrel = \haibao\cms\model\data\ArticleProImage::OLD_UPLOAD_PRO_IMG_1_1;
			}else{
				$disrel = \haibao\cms\model\data\ArticleProImage::OLD_UPLOAD_PRO_IMG_5_7;
			}
			$sql = 'delete from `content_photo` where article_id = %s and disrel = %s';
			$this->query ( $sql, array ($articleResult['OldPrimaryKey'],$disrel) );
			
			$valArr = array();
			$sql = "INSERT INTO `content_photo` (`image`,`date`,`article_id`,`title`,`blog_id`,`origin_url`,`pic_id`,`width`,`height`,`disrel`) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)";
			array_push ( $valArr, ltrim($imageInfo->Filename, '/') );
			array_push ( $valArr, date ( 'Y-m-d H:i:s' ) );
			array_push ( $valArr, $articleResult['OldPrimaryKey'] );
			array_push ( $valArr, $imageInfo->Description );
			array_push ( $valArr, 0 );
			array_push ( $valArr, ltrim($imageInfo->Filename, '/') );
			array_push ( $valArr, $imageResult['OldPrimaryKey'] );
			array_push ( $valArr, $imageInfo->Width );
			array_push ( $valArr, $imageInfo->Height );
			array_push ( $valArr, $disrel );
			$this->query($sql,$valArr);
			
			
			$sql = 'DELETE FROM `picsm_pic_obj` WHERE `obj_id` = %s and `disrel` = %s ';
			$this->query ( $sql, array ($articleResult['OldPrimaryKey'],$disrel) );
			
			$valArr = array();
			$sql = "INSERT INTO `picsm_pic_obj` (`module_id` ,`obj_id` ,`pic_id`,`disrel`,`adddate`) VALUES (%s,%s,%s,%s,%s)";
			array_push ( $valArr, 1 );
			array_push ( $valArr, $articleResult['OldPrimaryKey'] );
			array_push ( $valArr, $imageResult['OldPrimaryKey']);
			array_push ( $valArr, $disrel );
			array_push ( $valArr, date ( 'Y-m-d H:i:s' ) );
			$this->query($sql,$valArr);
		
		}
	}
	
	/**
	 * 同步删除老库的导读图信息
	 */
	private function delOldProImageByProId($articleId,$level){
		
		$sql="select OldPrimaryKey from DataMigrationMap where TableName = %s and PrimaryKey = %s ";
		$articleResult = $this->query($sql,array('Article',$articleId))->fetch_assoc();
		$oldArticleId = $articleResult['OldPrimaryKey'];
		if($oldArticleId){
			if($level == \haibao\cms\model\data\ArticleProImage::Level_ZERO){
				$disrel = \haibao\cms\model\data\ArticleProImage::OLD_SET_COVER_IMG_TYPE;
			}else if($level == \haibao\cms\model\data\ArticleProImage::Level_ONE){
				$disrel = \haibao\cms\model\data\ArticleProImage::OLD_UPLOAD_PRO_IMG_4_3;
			}else if($level == \haibao\cms\model\data\ArticleProImage::Level_TWO){
				$disrel = \haibao\cms\model\data\ArticleProImage::OLD_UPLOAD_PRO_IMG_1_1;
			}else{
				$disrel = \haibao\cms\model\data\ArticleProImage::OLD_UPLOAD_PRO_IMG_5_7;
			}
			$this->initOldDB();
			$sql = 'delete from `content_photo` where article_id = %s and disrel = %s';
			$this->query ( $sql, array ($oldArticleId,$disrel) );
			$sql = 'DELETE FROM `picsm_pic_obj` WHERE `obj_id` = %s and `disrel` = %s ';
			$this->query ( $sql, array ($oldArticleId,$disrel) );
		}
	}
	/**
	 * **********************文章老数据通过方法 end*********************************
	 */
}